Jon Levi
Jon Levi

Reputation: 51

*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.

enter image description here enter image description here

Upvotes: 0

Views: 3075

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41417

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

Upvotes: 6

Related Questions