Angular - 如何通过单击按钮销毁动态组件

Angular - How a destroy a Dynamically component by a button click

我正在使用它在 angular 中动态创建一个组件:

addComponent() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const compRef = viewContainerRef.createComponent(componentFactory);
    compRef.instance.someProperty = "some data";
}

因此每次执行该方法时都会创建一个新的组件实例。 到目前为止,一切都很好,但我的问题是:

如何使用按钮单击事件从 ChildComponent 本身销毁这些创建的组件?

1) 您可以跟踪变量或对象中的组件或所有组件并销毁它们:-

2) 或者,在 DOM 中加载新组件时销毁前一个组件,方法是在插入新组件之前存储最后一个引用和 .destroy() 它们。

.html

 <ng-container #dynamicComponentContainer id="dynamicComponentContainer"></ng-container>

.ts

         let componentRef = this.componentFactoryResolver.resolveComponentFactory(cmptName).create(this.injector);

                // check for duplicates and update with new one
             //   this.checkForDuplicateCmp(componentRef);

                componentRef.instance['inputdata'] = initCmpInputdata;
                let indexView = this.dynamicComponentContainer.length;
                this.dynamicComponentContainer.insert(componentRef.hostView, indexView);

      // keep refrence of lastComponent added to DOM
            this.lastComponent = componentRef;


  public remove component(){
    // destroy components as on click
      this.lastComponent.destroy();
     //or
     for (var j = 1; j < this.dynamicComponentContainer.length; j++) {
          this.dynamicComponentContainer.remove(j);  //or pass j 
      }
}