【发布时间】:2021-03-05 15:39:58
【问题描述】:
我使用*ngComponentOutlet 结构指令来显示动态组件。此动态组件必须根据某些条件显示。
例如,如果匹配了某个路由,则应显示该组件(搜索表单)。否则,它不应该显示。
我使用了以下代码:
<ng-container *ngIf="searchComponent">
<ng-container *ngComponentOutlet="searchComponent"></ng-container>
</ng-container>
地点:
import {SearchComponent} from '....';
public searchComponent: Type<any> | null;
...
show(): void {
this.searchComponent = SearchComponent;
}
hide(): void {
this.searchComponent = null;
}
这是可行的,但是使用上面的代码,当隐藏组件时,永远不会调用来自 SearchComponent 的 ngOnDestroy()。
在 Angular 文档 (https://angular.io/api/common/NgComponentOutlet) 中,我发现:
如果设置了假值,NgComponentOutlet 需要一个组件类型 视图将被清除,任何现有组件都将被销毁。
所以,我尝试使用布尔值,如下所示:
<ng-container *ngComponentOutlet="shouldShow && searchComponent"></ng-container>
和
从“....”导入 {SearchComponent};
public searchComponent: Type<any> = SearchComponent;
...
show(): void {
this.shouldShow = true;
}
hide(): void {
this.shouldShow = false;
}
这适用于 Stackblitz 演示:https://stackblitz.com/edit/angular-ivy-m4w2tk。但是在我的项目中使用上面的代码会产生编译错误:
Type 'false | Type<any>' is not assignable to type 'Type<any>'
我需要一个干净的方法来移除这个组件。
https://stackblitz.com/edit/angular-ivy-m4w2tk
谢谢。
【问题讨论】:
标签: angular