首页 > 解决方案 > ngIf 未显示组件

问题描述

我在 Angular 5 中创建了一个示例应用程序。我有两个名为app-parentapp-child的组件,每个组件都有一个示例文本。我的 App 组件中有一个变量,我需要在由变量值触发的时间显示上述组件。

这是代码。

应用组件.ts

export class AppComponent {
  val:string;
}

App.component.html:

<div *ngIf="!val; then r; else s">
    <ng-template #r>
        <app-parent></app-parent>
    </ng-template>
    <ng-template #s>
        <app-child></app-child>
    </ng-template>
</div>

我希望<app-parent>出现,但结果是什么都没有出现。这里有什么问题?

标签: angular

解决方案


https://stackblitz.com/edit/angular-zafvpx?file=src%2Fapp%2Fapp.component.html 应该做你想做的。

将您的条件放入 ng 容器中:

<ng-container *ngIf="val == 'r' && val.length > 0; then r; else s" ></ng-container>

请注意,当条件未满足时, else将始终可见。如果您不想采用 then-else 方法,我会将 *ngIf 放在组件的标签中以处理可见性,例如:

<app-parent *ngIf="val == 'r'"></app-parent>
<app-child *ngIf="val == 's'></app-child>

推荐阅读