我指的是这个Stackblitz示例,以动态创建表单并使用componentFactoryResolver对其进行调用。 但是,我还需要一个按钮来删除添加的表单。 假设用户单击按钮,然后添加了表单,如果用户再次单击,则添加了另一个表单。因此,我需要提供一个按钮来删除表单。 我该如何实现?
答案 0 :(得分:1)
创建这样的方法
removeComponent() {
this.container.clear();
}
更新: 删除特定的组件使用此:
首先创建一个组件数组
components = [];
然后
add(): void {
// create the component factory
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
// add the component to the view
const componentRef = this.container.createComponent(componentFactory);
this.components.push(componentRef );
// pass some data to the component
componentRef.instance.index = this._counter++;
}
removeComponent(componentIndex ) {
// Remove component from both view and array
this.container.remove(componentIndex );
this.components.splice(componentIndex, 1);
}
希望有帮助
答案 1 :(得分:0)
我做了你的例子的分叉:
https://stackblitz.com/edit/angular-dynamic-components-stack-55683353?file=src/app/app.component.ts
我在动态组件中添加了一个带有输出的按钮,以使用以下代码销毁它:
componentRef.instance.onRemove.subscribe(() => {
componentRef.destroy();
});
这里也有一些有关如何执行此操作的示例: Dynamically ADDING and REMOVING Components in Angular