Wolf359
Wolf359

Reputation: 2715

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 has a @HostBinding('hidden') decorated field:

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

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

Finally TabContainerComponent template is as follows :

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

The end goal is to toggle the visibility of a tab-item via click event.

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.

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.

How can I programmatically toggle visibility of <app-tab-item> components using @ContentChildren ?

Upvotes: 7

Views: 6738

Answers (1)

Wolf359
Wolf359

Reputation: 2715

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

I used this code + css class :

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

.hidden {
    display: none;
}

Upvotes: 6

Related Questions