Hide/show individual items inside ngFor

You’re hideme variable is global. Perhaps you could attach it to the current item:

<li *ngFor=" #item of items " >
  <a href="#" (onclick)="item.hideme = !item.hideme">Click</a>
  <div [hidden]="item.hideme">Hide</div>
</li>

Otherwise you need to use a dedicated object object from your component. Here is a sample:

<li *ngFor="let item of items " >
  <a href="#" (onclick)="hideme[item.id] = !hideme[item.id]">Click</a>
  <div [hidden]="hideme[item.id]">Hide</div>
</li>

Don’t forget to initialize the hideme object this way in your component:

hideme:<any> = {};

Edit

If you want to make this work like tabs, you need a bit more work 😉

<li *ngFor="let item of items " >
  <a href="#" (onclick)="onClick(item)">Click</a>
  <div [hidden]="hideme[item.id]">Hide</div>
</li>

And to display the clicked element and hide others:

onClick(item) {
  Object.keys(this.hideme).forEach(h => {
    this.hideme[h] = false;
  });
  this.hideme[item.id] = true;
}

Leave a Comment