角度-如何通过单击按钮破坏动态零部件

时间:2019-06-30 09:14:07

标签: angular angular7 angular8

我正在使用它动态地创建角度组件:

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

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

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

1 个答案:

答案 0 :(得分:2)

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