在ngFor中显示特定的Div

时间:2019-04-25 18:02:45

标签: javascript angular

我有一堆使用ngFor和用户信息的卡片。卡内有一个按钮,可显示该特定用户的旅行信息。

我创建了一个初始状态为display: none的div。我曾考虑过使用ngStyle来绑定display: block属性,但问题是所有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;
}

3 个答案:

答案 0 :(得分:3)

您需要在学生数组的每个元素上都有一个属性显示,然后根据索引启用/禁用,

<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;
}

答案 1 :(得分:3)

问题是您只有一个为所有变量设置的变量。

您将希望将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>

答案 2 :(得分:2)

您可以使用@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;
}

https://codesandbox.io/s/zwqoxp583x