简体   繁体   中英

*NgFor toggle show/hide individual element

I have that piece of code in 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>

And Angular code:

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

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

It works ok, but I need that when I clicked on button it hides that particular <span> container. I added images to illustrate what I want to do, but when i press button it hides all elements.

在此处输入图片说明 在此处输入图片说明

Add a property called show in the plate object and then change the value depend on the 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";
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM