Angular 角度-*ngComponentOutlet-破坏组件
我使用Angular 角度-*ngComponentOutlet-破坏组件,angular,Angular,我使用*ngComponentOutlet结构指令来显示动态组件。此动态组件必须根据某些条件显示 例如,如果某条路线匹配,则应显示组件(搜索表单)。否则,不应显示它 我使用了以下代码: <ng-container *ngIf="searchComponent"> <ng-container *ngComponentOutlet="searchComponent"></ng-container> </ng-c
*ngComponentOutlet
结构指令来显示动态组件。此动态组件必须根据某些条件显示
例如,如果某条路线匹配,则应显示组件(搜索表单)。否则,不应显示它
我使用了以下代码:
<ng-container *ngIf="searchComponent">
<ng-container *ngComponentOutlet="searchComponent"></ng-container>
</ng-container>
及
从“..”导入{SearchComponent}
public searchComponent: Type<any> = SearchComponent;
...
show(): void {
this.shouldShow = true;
}
hide(): void {
this.shouldShow = false;
}
公共搜索组件:类型。但在我的项目中使用上述代码会产生编译器错误:
Type'false | Type
谢谢。选项1
您还可以将组件ref设置为null:
模板:
<ng-container *ngComponentOutlet="component"></ng-container>
选项2
您可以将容器包装在另一个元素中,并在其上使用*ngIf,如下所示:
这看起来很像您尝试的代码,但该组件确实运行了OnDestroy生命周期挂钩
public searchComponent: Type<any> = SearchComponent;
...
show(): void {
this.shouldShow = true;
}
hide(): void {
this.shouldShow = false;
}
<ng-container *ngComponentOutlet="component"></ng-container>
public component = HelloWorld;
toggleHelloWorld(): void {
if (!this.component) {
this.component = HelloWorld;
} else {
this.component = null;
}
}
<ng-container *ngIf="show">
<ng-container *ngComponentOutlet="component"></ng-container>
</ng-container>