首页 > 解决方案 > 如何清除Angular中添加的元素?

问题描述

我有一个 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);
}

如果用户频繁更改选择框,则该项目将挂在下方。

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

标签: angular

解决方案


如果您ViewContainerRef用于保存注入的组件,您可以使用该clear()方法从视图中清除添加的组件。请注意,这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);

推荐阅读