[英]Angular - *ngComponentOutlet - destroy Component
我使用*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 需要一個組件類型,如果設置了一個虛假的值,視圖將被清除並且任何現有的組件都將被銷毀。
因此,我嘗試使用 boolean,如下所示:
<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
謝謝。
選項1
您還可以將組件 ref 設置為 null: https://stackblitz.com/edit/angular-ivy-tcbdsh?file=src%2Fapp%2Fapp.component.ts
模板:
<ng-container *ngComponentOutlet="component"></ng-container>
零件:
public component = HelloWorld;
toggleHelloWorld(): void {
if (!this.component) {
this.component = HelloWorld;
} else {
this.component = null;
}
}
選項 2
您可以將容器包裝在另一個元素中並在其上使用 *ngIf,如下所示: https://stackblitz.com/edit/angular-ivy-ct8xmh?file=src%2Fapp%2Fapp.component.ts
<ng-container *ngIf="show">
<ng-container *ngComponentOutlet="component"></ng-container>
</ng-container>
這看起來與您嘗試的代碼非常相似,但該組件確實運行了 OnDestroy 生命周期掛鈎。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.