隐藏/显示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个项目.问题在于它对两个项目都有效.因此,它在两个组件中隐藏并显示了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屋!