【问题标题】:Angular 6: Show / Hide component programmatically using @ContentChildren and @HostBinding?Angular 6:使用@ContentChildren 和@HostBinding 以编程方式显示/隐藏组件?
【发布时间】:2018-10-31 16:55:00
【问题描述】:

我想创建一个标签组件。这应该是最终结果:

<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') 修饰字段:

export class TabItemComponent {
    @HostBinding('hidden') isHidden = false;
    @Input() caption: string;
}

在 TabContainerComponent 中,我使用 @ContentChildren 来遍历选项卡项:

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 模板如下:

<div class="tab-title"
     *ngFor="let caption of tabItems">{{caption}}</div>
<ng-content></ng-content>

最终目标是通过点击事件来切换选项卡项的可见性。

当我运行代码选项卡标题显示正确但内容本身(app-tab-item caption="A" 到 "C")仍然可见时,设置 isHidden 不会切换可见性。

请注意,我不知道“app-tab-item”组件的数量,因为我可能会将“app-tab-container”放置在其他内容不同的地方。

如何使用 @ContentChildren 以编程方式切换 &lt;app-tab-item&gt; 组件的可见性?

【问题讨论】:

  • When I run the code tab titles display correctly but the content itself (app-tab-item caption="A" to "C") is still visible 你能用 stackblitz 重现它吗?
  • 对不起,这次不行,因为我不得不“笨拙”了很多代码。但尽管如此,我还是找到了解决问题的方法。 @HostBinding('class.hidden') @Input() hidden = false;

标签: angular


【解决方案1】:

我找到了解决方案。我现在没有尝试设置 [hidden] 属性,而是设置了一个“.hidden”css 类。它按预期工作:

export class TabItemComponent {
    @HostBinding('hidden') isHidden = false;
    @Input() caption: string;
}

我使用了这段代码 + css 类:

export class TabItemComponent {
    @HostBinding('class.hidden') @Input() hidden = false;
    @Input() caption: string;
}

.hidden {
    display: none;
}

【讨论】:

    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多