角度6:使用@ContentChildren和@HostBinding以编程方式显示/隐藏组件? [英] Angular 6: Show / Hide component programmatically using @ContentChildren and @HostBinding?
问题描述
我想创建一个选项卡组件.这应该是最终结果:
I want to create a tab component. This should be the end result:
<app-tab-container>
<app-tab-item caption="A">..contentA..</app-tab-item>
<app-tab-item caption="B">..contentB..</app-tab-item>
<app-tab-item caption="C">..contentC..</app-tab-item>
</app-tab-container>
TabItemComponent具有@HostBinding('hidden')装饰字段:
TabItemComponent has a @HostBinding('hidden') decorated field:
export class TabItemComponent {
@HostBinding('hidden') isHidden = false;
@Input() caption: string;
}
在TabContainerComponent中,我使用@ContentChildren遍历选项卡项:
In TabContainerComponent I use @ContentChildren to iterate through tab-items :
export class TabContainerComponent {
@ContentChildren(TabItemComponent) items: QueryList<TabItemComponent>;
tabItems: string[] = [];
ngAfterContentInit() {
this.items.forEach((item, idx) => {item.isHidden = true; this.tabItems.push(item.caption));
}
}
最后TabContainerComponent模板如下:
Finally TabContainerComponent template is as follows :
<div class="tab-title"
*ngFor="let caption of tabItems">{{caption}}</div>
<ng-content></ng-content>
最终目标是通过click事件切换选项卡项目的可见性.
The end goal is to toggle the visibility of a tab-item via click event.
当我运行代码标签标题时,显示正确,但内容本身(app-tab-item caption ="A"至"C")仍然可见,设置isHidden不会切换可见性.
When I run the code tab titles display correctly but the content itself (app-tab-item caption="A" to "C") is still visible, setting isHidden doesn't toggle visibility.
请注意,我不知道"app-tab-item"组件的数量,因为我可能会将"app-tab-container"放置在其他内容不同的地方.
Please note that I don't know the number of "app-tab-item" components, since I may place the "app-tab-container" elsewhere with different content.
如何使用@ContentChildren以编程方式切换< app-tab-item>
组件的可见性?
How can I programmatically toggle visibility of <app-tab-item>
components using @ContentChildren ?
推荐答案
我找到了解决方案.现在,我没有设置[hidden]属性,而是设置了一个".hidden" css类.它按预期工作:
I found the solution. Instead of trying to set the [hidden] attribute, I now set a '.hidden' css class. It works as expected :
export class TabItemComponent {
@HostBinding('hidden') isHidden = false;
@Input() caption: string;
}
我使用了这段代码+ CSS类:
I used this code + css class :
export class TabItemComponent {
@HostBinding('class.hidden') @Input() hidden = false;
@Input() caption: string;
}
.hidden {
display: none;
}
这篇关于角度6:使用@ContentChildren和@HostBinding以编程方式显示/隐藏组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!