ANGULAR 2+创建组件后将其删除 [英] ANGULAR 2+ Removal of the component after its creation
本文介绍了ANGULAR 2+创建组件后将其删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在动态创建一个组件,我想在1秒后删除它.
I'm dynamically creating a component, and I'd like to delete it after 1 second.
我想做类似的事情
ngOnInit(): void {
const time = timer(2000);
time.subscribe(() => {
REMOVE YOURSELF / THIS COMPONENT
});
}
推荐答案
为动态组件的component holder
发出指令,如下所示:
Make a directive for component holder
for dynamic component as below:
import { Directive, ViewContainerRef } from "@angular/core";
@Directive({
selector: '[component-holder]',
})
export class DynamicComponentDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
使用ViewChild
将其导入到您的组件中,如下所示:
Use ViewChild
to import it to your component as below:
@ViewChild(DynamicComponentDirective ) dynamicComponentDirective : DynamicComponentDirective ;
创建一些动态组件后,可以按如下所示将其删除.
After creating some dynamic component, you can remove it as below.
this.viewContainerRef = this.dynamicComponentDirective.viewContainerRef;
this.viewContainerRef.clear();
这篇关于ANGULAR 2+创建组件后将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文