Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: Show / Hide component programmatically using @ContentChildren and @HostBinding?

Tags:

angular

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 ?

like image 233
Wolf359 Avatar asked May 22 '18 02:05

Wolf359


1 Answers

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;
}
like image 186
Wolf359 Avatar answered Oct 23 '22 00:10

Wolf359