* Ng用于切换显示/隐藏单个元素

时间:2018-12-10 13:07:46

标签: javascript angular toggle ngfor

我有一段HTML代码:

<!-- Toggle show hide -->
    <ng-container *ngFor="let plate of plates; let i=index">
      <button (click)="toggle(plate)">{{i}}. {{ buttonName }}</button>
      <span *ngIf="!show">
        <i>{{i}}</i>
        <h1>{{ plate.PlateNumber }}</h1>
      </span>
    </ng-container>

和Angular代码:

toggle() {
    this.show = !this.show;

    // CHANGE THE NAME OF THE BUTTON.
    if (this.show)
      this.buttonName = "Show";
    else
      this.buttonName = "Hide";
  }

它可以正常工作,但我需要在单击按钮时将其隐藏在特定的<span>容器中。我添加了图像来说明我想要做什么,但是当我按下按钮时,它将隐藏所有元素。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:5)

show对象中添加一个名为plate的属性,然后根据click更改值。

 <ng-container *ngFor="let plate of plates; let i=index">
      <button (click)="toggle(plate)">{{i}}. {{ buttonName }}</button>
      <span *ngIf="!plate.show">
        <i>{{i}}</i>
        <h1>{{ plate.PlateNumber }}</h1>
      </span>
 </ng-container>

 toggle(plate) {
    plate.show = !plate.show;

    // CHANGE THE NAME OF THE BUTTON.
    if (plate.show)
      this.buttonName = "Show";
    else
      this.buttonName = "Hide";
  }