4 种不同变体的 ngFor 解决方案
ngFor solution for 4 different variations
我有 4 个成对拆分的按钮(A1、A2 和 B1、B2)。
我还有 4 个不同的段落,我想根据选中按钮的变体来显示...4 个变体应该是 A1B1、A1B2、A2B1 和 A2B2 ...
我设法 plunker 展示了一些基本原理,但仍然没有找到关于如何让 ngFor 仅将一个匹配段落加载到按钮组合的解决方案,那么,如果我单击按钮 A1和按钮 B2,它将只显示该代码的段落。
您需要使用 *ngIf 并有一种方法可以在发生任何更改时更新选择,我想这就是您要找的,
changeA( aValue ) {
this.currentA = aValue;
this.aElem = this.currentA;
this.selectedMonthElem = this.currentA;
this.setSelection();
}
changeB( bValue ) {
this.currentB = bValue;
this.bElem = this.currentB;
this.selectedYearElem = this.currentB;
this.setSelection();
}
setSelection() {
this.selection = this.currentA + this.currentB;
}
<button #elem1 value="A1" (click)="changeA(elem1.value)">A1</button>
<button #elem2 value="A2" (click)="changeA(elem2.value)">A2</button>
<button #elem3 value="B1" (click)="changeB(elem3.value)">B1</button>
<button #elem4 value="B2" (click)="changeB(elem4.value)">B2</button>
<p *ngIf="selection == 'A1B1'">Paragraph For A1B1</p>
<p *ngIf="selection == 'A1B2'">Paragraph For A1B2</p>
<p *ngIf="selection == 'A2B1'">Paragraph For A2B1</p>
<p *ngIf="selection == 'A2B2'">Paragraph For A2B2</p>
您仍然可以将段落内容放在对象中,并使整个结构像地图一样。这样我们就不需要使用多个 *ngIf 和硬编码。如果您更喜欢该解决方案,请告诉我
我有 4 个成对拆分的按钮(A1、A2 和 B1、B2)。
我还有 4 个不同的段落,我想根据选中按钮的变体来显示...4 个变体应该是 A1B1、A1B2、A2B1 和 A2B2 ...
我设法 plunker 展示了一些基本原理,但仍然没有找到关于如何让 ngFor 仅将一个匹配段落加载到按钮组合的解决方案,那么,如果我单击按钮 A1和按钮 B2,它将只显示该代码的段落。
您需要使用 *ngIf 并有一种方法可以在发生任何更改时更新选择,我想这就是您要找的,
changeA( aValue ) {
this.currentA = aValue;
this.aElem = this.currentA;
this.selectedMonthElem = this.currentA;
this.setSelection();
}
changeB( bValue ) {
this.currentB = bValue;
this.bElem = this.currentB;
this.selectedYearElem = this.currentB;
this.setSelection();
}
setSelection() {
this.selection = this.currentA + this.currentB;
}
<button #elem1 value="A1" (click)="changeA(elem1.value)">A1</button>
<button #elem2 value="A2" (click)="changeA(elem2.value)">A2</button>
<button #elem3 value="B1" (click)="changeB(elem3.value)">B1</button>
<button #elem4 value="B2" (click)="changeB(elem4.value)">B2</button>
<p *ngIf="selection == 'A1B1'">Paragraph For A1B1</p>
<p *ngIf="selection == 'A1B2'">Paragraph For A1B2</p>
<p *ngIf="selection == 'A2B1'">Paragraph For A2B1</p>
<p *ngIf="selection == 'A2B2'">Paragraph For A2B2</p>
您仍然可以将段落内容放在对象中,并使整个结构像地图一样。这样我们就不需要使用多个 *ngIf 和硬编码。如果您更喜欢该解决方案,请告诉我