代码之家  ›  专栏  ›  技术社区  ›  Tobias

如何清除角度中添加的元素?

  •  0
  • Tobias  · 技术社区  · 6 年前

    我有一个select字段,它根据值在父元素中插入一个组件。 代码示例:

    @ViewChild('parentStuff', { read: ViewContainerRef }) container: ViewContainerRef;
    
    constructor(
        private _cfr: ComponentFactoryResolver
    ) {}
    
    onChange(event): void {
        // how to clear here the other components?
        let comp = this._cfr.resolveComponentFactory(SubRule);
        this.container.createComponent(comp);
    }
    

    如果用户经常更改选择框,则项目将挂在下面。

    如何删除以前添加的项目?

    1 回复  |  直到 6 年前
        1
  •  0
  •   nircraft    6 年前

    如果您正在使用 ViewContainerRef 要保留注入的组件,可以使用 clear() 方法从视图中清除添加的组件。请注意 清除() 将删除添加到容器中的所有元素。

    this.container.clear();
    

    如果您只想删除 特定成分 ,您可以使用它的索引来查找和从视图中删除它:

      let componentRef: ComponentRef<MyComponent> = 
           this.container.createComponent(componentFactory);
      const containerIndex: number = this.container.indexOf(componentRef)
    
        // removing component from container
        this.container.remove(containerIndex);
    
    推荐文章