【问题标题】:Angular - *ngComponentOutlet - destroy ComponentAngular - *ngComponentOutlet - 销毁组件
【发布时间】: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;
}

这是可行的,但是使用上面的代码,当隐藏组件时,永远不会调用来自 SearchComponentngOnDestroy()

在 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&lt;any&gt;' is not assignable to type 'Type&lt;any&gt;'

我需要一个干净的方法来移除这个组件。

https://stackblitz.com/edit/angular-ivy-m4w2tk

谢谢。

【问题讨论】:

    标签: angular


    【解决方案1】:

    选项 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 生命周期挂钩。

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 2019-07-28
      • 1970-01-01
      • 2020-08-31
      • 2021-04-26
      • 2018-12-17
      • 2017-08-26
      • 1970-01-01
      • 2015-10-19
      相关资源
      最近更新 更多