[英]Angular - How a destroy a Dynamically component by a button click
我正在使用它動態地創建一個角組件:
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()
銷毀前一個組件。
<ng-container #dynamicComponentContainer id="dynamicComponentContainer"></ng-container>
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.