在 ngFor 中隐藏/显示单个项目 [英] Hide/show individual items inside ngFor
问题描述
我需要显示/隐藏部分组件.这是 Angular2 示例.
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>
假设我们只有 2 个项目.这里的问题是它适用于这两个项目.所以它隐藏和显示 both 组件中的 div 部分.如果我们能有这样的东西就完美了:
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 ?
推荐答案
你的 hideme
变量是全局的.也许您可以将其附加到当前项目:
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>
不要忘记在您的组件中以这种方式初始化 hideme
对象:
Don't forget to initialize the hideme
object this way in your component:
hideme:<any> = {};
编辑
如果你想让它像标签一样工作,你需要做更多的工作;-)
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;
}
这篇关于在 ngFor 中隐藏/显示单个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!