我有一堆使用 ngFor 和用户信息的卡片。卡片内有一个按钮,可以显示该特定用户的旅行信息。
我创建了一个初始状态为 display: none
的 div。我考虑过使用 ngStyle
在单击时绑定(bind) display: block
属性,但问题是所有 div 都在显示,而不仅仅是我需要的特定 div。
关于我如何做到这一点有什么建议吗?
html
<div class="col s12 m6 l4" *ngFor="let student of students; let i = index">
<i class="material-icons" (click)="showBox()">access_alarm</i>
<div class="travel-info" [ngStyle]="{'display': boxDisplay == true ? 'block' : 'none'}" >
<app-travel-info ></app-travel-info>
</div>
</div>
ts
boxDisplay = false;
showBox() {
this.boxDisplay = true;
}
最佳答案
问题是您只有一个为所有变量设置的变量。
您需要将 showBox 重构为这样的东西。
TS
this.boxDisplay = this.students.map(s => false);
showBox(index) {
this.boxDisplay[index] = true;
}
HTML
<div class="col s12 m6 l4" *ngFor="let student of students; let i = index">
<i class="material-icons" (click)="showBox(i)">access_alarm</i>
<div class="travel-info" [ngStyle]="{'display': boxDisplay[i] == true ? 'block' : 'none'}" >
<app-travel-info ></app-travel-info>
</div>
</div>
如果是我,我会使用 ngIf 而不是 ngStyle。
<div class="col s12 m6 l4" *ngFor="let student of students; let i = index">
<i class="material-icons" (click)="showBox(i)">access_alarm</i>
<div class="travel-info" *ngIf="boxDisplay[i]" >
<app-travel-info ></app-travel-info>
</div>
</div>
关于javascript - 在 ngFor 中显示特定的 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55855206/