Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Hide/show individual items inside ngFor

I need to show / hide part of component. Here is Angular2 example.

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

Suppose we have only 2 items. Problem here that it works on both items. So it hides and shows div part in both components. It could be perfect if we could have something like this:

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

So is there some simple way to solve this problem ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...