我正在动态创建一个组件,我想在1秒后删除它。
我想做类似的事情
ngOnInit(): void {
const time = timer(2000);
time.subscribe(() => {
REMOVE YOURSELF / THIS COMPONENT
});
}
答案 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();