ANGULAR 2+创建组件后将其删除

时间:2018-09-06 10:52:48

标签: angular

我正在动态创建一个组件,我想在1秒后删除它。

我想做类似的事情

  ngOnInit(): void {
    const time = timer(2000);
    time.subscribe(() => {
       REMOVE YOURSELF / THIS COMPONENT
    });
  }

1 个答案:

答案 0 :(得分:1)

为动态组件的component holder发出如下指令:

import { Directive, ViewContainerRef } from "@angular/core";

@Directive({
    selector: '[component-holder]',
})
export class DynamicComponentDirective {
    constructor(public viewContainerRef: ViewContainerRef) { }
}

使用ViewChild将其导入到您的组件中,如下所示:

@ViewChild(DynamicComponentDirective ) dynamicComponentDirective : DynamicComponentDirective ;

创建一些动态组件后,可以按如下所示将其删除。

this.viewContainerRef = this.dynamicComponentDirective.viewContainerRef;
this.viewContainerRef.clear();