angular - 如何在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);
...
}
}
但我不确定这是一个好的解决方案
解决方案
但我不确定这是一个好的解决方案
我遇到了同样的问题。这ComponentRef.destroy
也破坏了主机容器,因此通过创建一个子节点并将其用作主机,原始父容器保持不变。
因此,从我的角度来看,这绝对是一个很好的解决方案。
推荐阅读
- java - 如何自定义应用程序日志?
- flutter - 如何在颤动中打开默认电子邮件应用收件箱?
- python-3.x - 从 .docx / .doc 文件中提取突出显示的文本
- visual-studio-2017 - 尝试使用属性时的 Magick++ 链接错误
- node.js - 如何使用 dockerfile 启动 AWS SAM
- excel - 使用 matlab activex 服务器选择多个范围
- javascript - 无法在 JavaScript 中打印出正则表达式的匹配项
- ios - 如何保存应用于 UIView 的 CATransform3D
- spring-boot - 当我将 setHttpOnly 和 setSecure 设置为 true 时,Cookie 为空
- java - 将变量从一个 POJO 复制到另一个