angularng-container

ng-container with *ngIf else template don't work with ContentChildren QueryList


I'm trying to dynamicly change content of component by @ContentChildren and QueryList usign ng-container *ngIf="condition; else tplRef", when condition is true ng-container content is visible by QueryList but when condition is false, ng-template content isn't visible.

My goal is to display different element based on condition which will be visible by `Query

https://stackblitz.com/edit/angular-g2v6nd


Solution

  • You need to keep <ng-template #ref>... </ng-template> within <app-container>

    Try like this:

    Working Demo

    <app-container>
        <app-container-item name="Item 1"></app-container-item>
        <app-container-item name="Item 2"></app-container-item>
    
        <!-- work fine if true -->
        <ng-container *ngIf="true; else ref">
            <app-container-item name="Item when true"></app-container-item>
        </ng-container>
        <!-- should display content from ref, but don't work :( -->
        <ng-container *ngIf="false; else ref">
            <app-container-item name="Item when true"></app-container-item>
        </ng-container>
    
        <ng-template #ref>
            <app-container-item name="Item when false"></app-container-item>
        </ng-template>
    
    </app-container>