Angular中如何修改removeComp方法删除ComponentFactoryResolver创建的指定组件
实现指定动态组件删除的修改方案
你需要先存储每次动态创建的组件引用,再根据引用或者索引定位要删除的目标组件即可,具体修改步骤如下:
- 先在宿主组件类中定义数组,存储动态创建的组件实例
import { ComponentRef } from '@angular/core'; // 组件类内部定义属性 components: ComponentRef<OneComponent>[] = [];
- 修改
addComp方法,把每次创建的组件实例存入数组
addComp(): void { const componentFactory = this.componentFactoryResolver.resolveComponentFactory(OneComponent); const viewContainerRef = this.injectComp.viewContainerRef; const componentRef = viewContainerRef.createComponent(componentFactory); // 组件引用存入数组 this.components.push(componentRef); }
- 改造
removeComp方法,可根据实际使用场景选择以下两种实现:
方案1:按索引删除(适合可获取到组件创建顺序索引的场景)
索引从0开始计数,对应第一个创建的组件:
removeComp(index: number): void { const viewContainerRef = this.injectComp.viewContainerRef; // 校验索引合法性 if (index < 0 || index >= this.components.length) return; // 移除视图容器中对应索引的组件 viewContainerRef.remove(index); // 销毁组件实例,避免内存泄漏,同时触发组件的ngOnDestroy生命周期 this.components[index].destroy(); // 清空存储数组中对应的引用 this.components.splice(index, 1); }
方案2:按组件实例删除(适合已经拿到要删除的组件对象的场景)
removeComp(targetComponent: ComponentRef<OneComponent>): void { const viewContainerRef = this.injectComp.viewContainerRef; // 查找目标组件在存储数组中的索引 const index = this.components.findIndex(item => item === targetComponent); if (index === -1) return; viewContainerRef.remove(index); targetComponent.destroy(); this.components.splice(index, 1); }
如果需要通过组件内部的自定义标识(比如组件内定义的id、name属性等)删除,只需要修改findIndex的判断逻辑即可,示例:
const index = this.components.findIndex(item => item.instance.id === targetId);
内容的提问来源于stack exchange,提问作者teumec
相关产品推荐
相关产品推荐

