angular - ngIf 未显示组件
问题描述
我在 Angular 5 中创建了一个示例应用程序。我有两个名为app-parent和app-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>
出现,但结果是什么都没有出现。这里有什么问题?
解决方案
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>
推荐阅读
- redux - 如何在 redux store 中显示更新后的状态
- go - 在循环内创建 JWT 令牌时在 jwt-go 中获取相同的令牌
- module - 如何将特征的实现拆分为多个文件?
- python - 我在 settings.py 上实现了电子邮件设置,但是当我提交表单时它不起作用
- python - 删除包含 NaN 的 Pandas Dataframe 的前导行
- php - 可访问的敏感 URL
- android - 运行我的项目时显示此消息“Android 资源链接失败”
- c# - 如何反序列化 IPGeoLocation API 返回的 json 并在 .chtml 视图中使用
- c - C 编程中的 Malloc - 不兼容的指针类型
- sql - 存储数据排序:非聚集主键覆盖聚集索引