繁体   English   中英

在 angular 组件中通过 id 删除动态创建的元素

[英]Remove dynamically created element by id in angular component

我已经向组件添加了一个外部脚本,如下所示:

ngAfterViewInit() {
  let s = document.createElement("script");
  s.id = "hs-script-loader";
  s.async = true;
  s.src = "//some-url.com/12345.js";
  this.element.nativeElement.appendChild(s);
}

该脚本实际上加载了一个实时聊天小部件,该小部件是在加载脚本时在 DOM 中动态创建的。

当组件被销毁时,我想从 DOM 中删除该元素,但我不确定如何创建对动态创建元素的引用。

我见过使用 elementRef 的示例,但这假设您可以控制元素并且它不是动态创建的。

我如何动态定位元素,类似于使用事件委托但在 angular 中?

您可以将#local 引用添加到包含您的元素的ng-containerdiv ,然后在您的代码中,使用@ViewChild链接引用,最后使用以下命令将其删除:

@ViewChild('yourLocalReferenceHTMLname') private yourLocalReferenceHTMLname: ElementRef;

this.yourLocalReferenceHTMLname.nativeElement.remove();

无论如何,尽量不要使用 elementRef [来自 Angular 文档]:

当需要直接访问 DOM 时,使用elementRef API作为最后的手段。 请改用 Angular 提供的模板和数据绑定。 或者,您可以使用Renderer2 ,它提供了 API ,即使不支持直接访问本机元素也可以安全使用。

依赖直接 DOM 访问会在您的应用程序和渲染层之间创建紧密耦合,这将使得无法将两者分开并将您的应用程序部署到 web 工作器中。

从字面上看,来自这篇 render2 文章HERE

为什么不是 ElementRef?

我们可以使用 ElelemtRef 的 nativeElement 属性来操作 DOM。nativeElement 属性包含对底层 DOM object 的引用。 这使我们可以绕过 Angular 直接访问 DOM。

使用它没有任何问题,但不建议使用它,原因如下:

Angular keeps the Component & the view in Sync using Templates, data binding & change detection, etc. All of them are bypassed when we update the DOM Directly.

DOM Manipulation works only in Browser. You will not able to use the App in other platforms like in a web worker, in Server (Server-side rendering), or in a Desktop, or in the mobile app, etc where there is no browser.

The DOM APIs do not sanitize the data. Hence it is possible to inject a script, thereby, opening our app an easy target for the XSS injection attack.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM