繁体   English   中英

Angular - *ngComponentOutlet - 销毁组件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM