首页 > 解决方案 > 带有 *ngIf else 模板的 ng-container 不适用于 ContentChildren QueryList

问题描述

我正在尝试通过@ContentChildrenQueryListussign动态更改组件的内容ng-container *ngIf="condition; else tplRef",当condition真正的ng-container内容是可见的,QueryList但当condition是假的时候,ng-template内容是不可见的。

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

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

标签: angularng-container

解决方案


你需要保持<ng-template #ref>... </ng-template><app-container>

试试这样:

工作演示

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

推荐阅读