首页 > 解决方案 > 如何删除由模板引用创建的组件?

问题描述

我正在尝试获取对从模板生成的组件的引用,以便以后可以手动销毁它。这可能吗?

在这个例子中,我有一个模板,然后我用createEmbeddedView它来创建一个新实例,然后将它添加到当前视图中。这适用于我的意图。

我已经尝试过并且能够删除my-component,但我不确定如何访问它。我知道我可以使用 直接访问该组件@ViewChildren(),但是如何获取ComponentRef该组件的 a 并销毁它以便将其从 DOM 中删除?

@Component({
  template: `
  <button (click)="open()"></button>

  <ng-template #template let-message="message">
    <my-component>{{message}}</my-component>
  </ng-template>
  `
})
export ExampleComponent {

  @ViewChild('template')
  template!: TemplateRef<object>;

  @ViewChildren(MyComponent)
  myComponents!: QueryList<MyComponent>;

  constructor(
    private viewContainerRef: ViewContainerRef
  ){ }

  open() {
    const template = this.template.createEmbeddedView({message: 'hello'});
    this.viewContainerRef.insert(template);
  }
}

如果从最后一个到第一个删除,则有效

我能够使用它来工作remove(),但是这是一个好方法吗?

  ngAfterViewInit() {
    this.myComponents.changes.subscribe(() => {
      this.myComponents.forEach((cmp, idx) => {
        if (!cmp.isOpen) {
          cmp.open();
          let sub = cmp.closed.subscribe(() => {
            this.viewContainerRef.remove(idx);
            sub.unsubscribe();
          });
        }
      });
    });
  }

标签: javascriptangular

解决方案


只需this.viewContainerRef.insert(template)使用this.viewContainerRef.remove(0)or还原this.viewContainerRef.remove(this.viewContainerRef.length - 1)。这将卸载组件并释放内存,因为不会留下任何引用(const template仅限于open函数)


推荐阅读