首页 > 解决方案 > 从 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 在内部触发,当从其中删除组件时必须全部执行(就像所有连接到它的边也应该被删除,等等)

有谁知道这里发生了什么以及如何解决?任何帮助表示赞赏。

标签: javascriptjqueryangularjsplumb

解决方案


正如上面评论中提到的。以 Angular 方式操作由 Angular 创建的 DOM 元素的一种方法是使用detach()ViewContainerRef 类的方法。像这样的东西:

@ViewChild("containerNode", { read: ViewContainerRef }) cardContainer: ViewContainerRef;

...

// To remove/detach component in Angular way
this.cardContainer.detach();

推荐阅读