首页 > 解决方案 > 如何在Angular中替换动态元素

问题描述

在我的应用程序中,我使用了一个动态组件。要插入它,我调用onTooltipVisible,我将HTMLDivElement其作为参数传递,如下所示:

<div id="tooltip-container"></div>

它是一个父级,我需要在其中插入我的组件,以便我的组件进入 shadow-root

<div id="tooltip-container">
  #shadow-root(open)
    ...
</div>

但是当我改变一些东西然后removeTooltip()调用时,这个函数从 DOM 中删除,不仅#shadow-root是我的组件,而是整个父容器,所以在接下来的步骤中我不能再次插入我的组件,因为不再有父组件。

所以我的问题是,我怎样才能只删除这个 shadow-root 并离开父级,或者也许有一些方法可以再次将其替换为空 div id="tooltip-container"

现在我的代码如下所示:

ngOnDestroy(): void {
  this.removeTooltip();
}

onTooltipVisible(container: HTMLDivElement): void {
  if (container) {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(TooltipComponent);
    this.tootipComponentRef = componentFactory.create(this.injector, [], container);
    this.applicationRef.attachView(this.tooltipComponentRef.hostView);
  } else {
    this.removeTooltip();
  }
}

removeTooltip(): void {
  if (this.tooltipComponentRef) {
    this.applicationRef.detachView(this.tooltipComponentRef.hostView);
    this.tooltipComponentRef.destroy();
  }
}

非常感谢您的帮助!


更新:

如果我再添加一个容器 beetwen 我的组件和父级一切正常

onTooltipVisible(container: HTMLDivElement): void {
  if (container) {
    const componentContainer = document.createElement('div');
    container.appendChild(componentContainer);
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(TooltipComponent);
    this.tootipComponentRef = componentFactory.create(this.injector, [], componentContainer);
      ...
   }
}

但我不确定这是一个好的解决方案

标签: angulartypescript

解决方案


但我不确定这是一个好的解决方案

我遇到了同样的问题。这ComponentRef.destroy也破坏了主机容器,因此通过创建一个子节点并将其用作主机,原始父容器保持不变。

因此,从我的角度来看,这绝对是一个很好的解决方案。


推荐阅读