带有* ngIf else模板的ng-container不适用于ContentChildren QueryList

时间:2019-11-28 08:29:00

标签: angular ng-container

我正在尝试通过@ContentChildrenQueryList使用ng-container *ngIf="condition; else tplRef"动态更改组件的内容,当condition为真时,ng-container的内容可由{ {1}},但如果QueryList为假,则condition内容不可见。

我的目标是根据查询可以显示的条件显示不同的元素

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

2 个答案:

答案 0 :(得分:1)

您需要将<ng-template #ref>... </ng-template>保留在<app-container>

尝试这样:

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>

答案 1 :(得分:1)

您已将<ng-template #ref><app-container>分开,必须将<ng-template #ref>保留在<app-contianer>内。 这就是解决方案!