【问题标题】:Angular - How a destroy a Dynamically component by a button clickAngular - 如何通过单击按钮来销毁动态组件
【发布时间】:2019-11-11 09:39:56
【问题描述】:

我正在使用它来动态创建 angular 组件:

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

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

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

【问题讨论】:

标签: angular angular7 angular8


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-01-18
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2019-07-28
    • 1970-01-01
    相关资源
    最近更新 更多