嘿...我找到了一篇关于使用动态组件加载器和处置方法添加和删除组件的帖子。我想一次销毁所有创建的组件。我有 plunker demo以及我找到演示的来源 Angular 2 - Adding / Removing components on the fly ...
我知道我想将所有 componentref
存储在一个数组中然后迭代它们并处理它......但我无法让它工作......请帮助我如何销毁所有组件.
remove() {
this._ref.dispose();
}
这就是我销毁单个组件的方式...如何一次销毁所有组件?
最佳答案
完成您所要求的操作的最简单方法是在添加 ComponentRef
时跟踪它们,并在每个中调用 dispose()
当你想删除它们时的循环。参见 updated plunk
export class App {
...
private _children:ComponentRef[] = [];
add() {
this._dcl.loadIntoLocation(DynamicCmp, this._e, 'location').then((ref) => {
...
this._children.push(ref);
});
}
removeall(){
this._children.forEach(cmp=>cmp.dispose());
this._children = []; // not even necessary to get the components off the screen
}
}
如果出于某种原因只调用一次 dispose()
非常重要,您可以创建一个“容器”,将您的 DynamicComponent
作为其子项添加,然后处理容器,自动处理它的 child 。
话虽如此,我无法想象我更愿意这样做而不是添加四行代码来实现我上面概述的内容......
说完全部:如果有一种方法可以使用数据绑定(bind)来完成您想要做的事情,那么您应该更倾向于使用它而不是求助于 DynamicComponentLoader
除非你有充分的理由不这样做。
我会第一个告诉你有 需要 DCL 的用例,但根据我(虽然简短)的经验,对于每五个我最初认为需要的用例,我想出了在稍微考虑一下之后,至少有三个数据绑定(bind)解决方案。
在这种情况下,这样做很简单 - 请参阅 other updated plunk :
@Component({
selector: 'my-app',
template : `
<button (click)="add()">Add new component</button>
<button (click)="removeAll()">Remove All</button>
<template ngFor #child [ngForOf]="children">
<div [dynamicCmp]="child"></div>
</template>
`,
directives:[DynamicCmp]
})
export class App {
children:number[] = [];
add() {
this.children.push(this.children.length+1);
}
removeAll(){
this.children = [];
}
}
关于typescript - 如何销毁在 angular2 中使用 DynamicComponentLoader 创建的所有组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34585357/