我正在尝试实现ngFor显示的项目列表的切换。就像当我单击切换按钮时,它应该显示特定于该行的div。 另外,我必须相应地应用样式。 现在我看到当我单击一个按钮时所有行都显示div。这里有任何建议吗?
export class VentClass {
toggelFlagvfe: boolean = false;
gDatas: any[];
constructor() {
this.gDatas = [{"ID":"85","Source":"Local","Eqpmnts":[{"ID":"10","CreatedBy":"jmzw"},{"ID":"10","CreatedBy":"jmzw"}]},{"ID":"86","Source":"Local","Eqpmnts":[{"ID":"10","CreatedBy":"jmzw"}]},{"ID":"87","Source":"EC","Eqpmnts":[]}]
}
toggleSection(item) {
if (this.toggelFlagvfe == true) {
this.toggelFlagvfe = false;
}
else {
this.toggelFlagvfe = true;
}
}
}
<ion-row *ngFor="let item of gDatas">
<ion-col col-1>
<button (click)="toggleSection(item)" detail-none
[ngClass]="{'section-active1': toggelFlagvfe, 'section1': !toggelFlagvfe}">
<ion-icon item-left name="arrow-dropright" *ngIf="!toggelFlagvfe"></ion-icon>
<ion-icon item-left name="arrow-dropdown" *ngIf="toggelFlagvfe"></ion-icon>
</button>
</ion-col>
<ion-col col-2>
<ion-input type="number" [(ngModel)]="item.ID" text-wrap></ion-input>
</ion-col>
<ion-col col-2>
<ion-label>{{item.Source}} </ion-label>
</ion-col>
<div *ngIf="toggelFlagvfe">
<ion-grid >
<ion-row *ngFor="let eqpm of item.Eqpmnts" nowrap>
<ion-col>
<ion-label>{{eqpm.ID}} </ion-label>
<ion-label>{{eqpm.CreatedBy}} </ion-label>
</ion-col>
</ion-row>
</ion-grid>
</div>
</ion-row>
答案 0 :(得分:1)
您正在使用一个布尔值来控制gDatas
中所有元素的切换。因此,每当toggelFlagve
设置为true时,模板中的*ngIf
都会对*ngFor
循环的所有成员为true。
相反,您可以做的是为gDatas
的每个成员提供一个“切换”布尔键,当您单击按钮元素时,该键将变为true:
//your component template
<ion-row *ngFor="let item of gDatas; index as i">
<ion-col col-1>
<button (click)="toggleSection(i)" detail-none
[ngClass]="{'section-active1': item.toggle, 'section1': !item.toggle}">
<ion-icon item-left name="arrow-dropright" *ngIf="!item.toggle"></ion-icon>
<ion-icon item-left name="arrow-dropdown" *ngIf="item.toggle"></ion-icon>
</button>
</ion-col>
<!-- other stuff is the same -->
<div *ngIf="item.toggle">
<!-- contents are the same here -->
</div>
</ion-row>
//your component.ts
export class VentClass {
gDatas: any[];
constructor() {
this.gDatas = [{toggle: false,"ID":"85","Source":"Local","Eqpmnts":[{"ID":"10","CreatedBy":"jmzw"},{"ID":"10","CreatedBy":"jmzw"}]},{toggle: false,"ID":"86","Source":"Local","Eqpmnts":[{toggle: false,"ID":"10","CreatedBy":"jmzw"}]},{toggle: false,"ID":"87","Source":"EC","Eqpmnts":[]}]
}
toggleSection(item: number) {
this.gDatas[item].toggle = !this.gDatas[item].toggle;
}
}
因此,这里的最大区别是toggleSection
现在使用gDatas
中的数组索引来确定需要切换的元素,然后在HTML模板中使用toggelFlagvfe
而不是使用item.toggle
确定是否切换了每个单独的元素。