ANGULAR 2+ Removal of the component after its creation

后端 未结 1 914
太阳男子
太阳男子 2021-01-29 02:35

I\'m dynamically creating a component, and I\'d like to delete it after 1 second.

I want to do something like that

  ngOnInit(): void {
    const time =          


        
相关标签:
1条回答
  • 2021-01-29 03:12

    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) { }
    }
    

    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();
    
    0 讨论(0)
提交回复
热议问题