javascript - 从 jQuery 中删除动态组件会弄乱 ViewContainerRef 容器
问题描述
我有一个 Angular 2+ 应用程序,我在其中创建了一堆像这样的动态组件 -
@ViewChild("containerNode", { read: ViewContainerRef }) cardContainer;
const factory = this.ComponentFactoryResolver.resolveComponentFactory(CardComponent);
const ref = this.cardContainer.createComponent(factory);
我正在使用 jsPlumb(jQuery 版本),将这些创建的组件绘制到画布上。一旦这些元素成为 jsPlumb 实例的一部分,jsPlumb 就会提供删除元素、添加端点等的选项。
现在,在用户(单击)事件中,我正在删除用户单击的元素,如下所示 -
this.jsPlumbInstance.remove(ref.location.nativeElement);
在内部我假设这只是一个 jQuery 删除。我面临的问题是,在使用上述代码删除此元素后,我无法使用 ViewContainerRef 添加任何新组件。这条线执行后,当我这样做时
const factory = this.ComponentFactoryResolver.resolveComponentFactory(CardComponent);
const ref = this.cardContainer.createComponent(factory);
ref.location.nativeElement 的父节点为空。我怀疑使用 jQuery remove 删除组件会以某种方式弄乱容器并且不会将新组件正确添加到父级。注意,我必须做一个 jsPlumb.remove 因为有几个其他相关事件将由 jsPlumb 在内部触发,当从其中删除组件时必须全部执行(就像所有连接到它的边也应该被删除,等等)
有谁知道这里发生了什么以及如何解决?任何帮助表示赞赏。
解决方案
正如上面评论中提到的。以 Angular 方式操作由 Angular 创建的 DOM 元素的一种方法是使用detach()
ViewContainerRef 类的方法。像这样的东西:
@ViewChild("containerNode", { read: ViewContainerRef }) cardContainer: ViewContainerRef;
...
// To remove/detach component in Angular way
this.cardContainer.detach();
推荐阅读
- vue.js - Vue API 数据在窗口刷新时消失了
- django - 当应用程序关闭时获取有关 React-Native 的通知(如果可能,使用 websockets)
- python - 如何始终为使用 PyTest 测试的 Flask 应用程序提供上下文?
- windows - 根据子文件夹名称替换多个 .txt 文件中的单词的 Bat 脚本
- r - 如何增加 R 中面板图的高度?
- php - Laravel 8 通过 SFTP 存储文件
- javascript - 我正在尝试在悬停时更改多个按钮的文本内容
- sql - 有没有办法计算唯一对并按其他列分组
- laravel - VueJS i18n - 如何更改翻译文件中的变量前缀
- selenium - 如果任何操作方法无法执行,测试不会失败 - selenium & TestNG