我有一堆使用ngFor和用户信息的卡片。卡内有一个按钮,用于显示该特定用户的旅行信息。
我用初始状态display: none
创建了一个div。我想在点击时使用ngStyle
绑定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;
}
您可以使用@ViewChildren。我给你这个例子:
你的HTML:
<div class="student-container" *ngFor="let s of students; let i = index">
<span>Name: {{s.name}} - Index: {{i}}</span>
<div class="student-box" #boxes>
<span>Hey! I'm opened.</span>
<span>My Secret Number is: {{s.secretNumber}}</span>
</div>
<button (click)="toggleBox(i)">Click Me!</button>
</div>
你的组件:
import { Component, ViewChildren, QueryList, ElementRef } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
@ViewChildren("boxes") private boxes: QueryList<ElementRef>;
students = [
{ name: "Peter", secretNumber: "88" },
{ name: "Laura", secretNumber: "45" },
{ name: "Paul", secretNumber: "13" }
];
toggleBox(index) {
let nativeElement = this.boxes.toArray()[index].nativeElement;
nativeElement.style.display =
nativeElement.style.display === "none" || !nativeElement.style.display
? "block"
: "none";
}
}
你的CSS:
.student-container {
background: lightblue;
margin: 10px;
padding: 10px;
}
.student-box {
display: none;
}
你需要有一个属性显示学生数组的每个元素,然后根据索引启用/禁用,
<div class="col s12 m6 l4" *ngFor="let student of students; let i = index">
<i class="material-icons" (click)="showBox(student)">access_alarm</i>
<div class="travel-info" [ngStyle]"{'display': student.boxDisplay == true ? 'block' : 'none'}" >
<app-travel-info ></app-travel-info>
</div>
</div>
showBox(student:any) {
student.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>