简体   繁体   English

从 angular 中的外部 javascript 文件中销毁元素

[英]Destroying element from an external javascript file in angular

I am currently adding an element from an external javascript source upon OnInit using this我目前正在使用这个在 OnInit 上添加来自外部 javascript 源的元素

HTML HTML

<div id='jsContainer' #jsContainer></div>

TS FILE文件

let jsDiv = document.getElementById('jsContainer')
script.src = url
script.async = true;
this._renderer2.appendChild(jsDiv,script);

Now I want to destroy or remove the element upon ngOnDestroy现在我想在 ngOnDestroy 上销毁或删除元素

I tried to do this我试着这样做

if (document.getElementById('jsContainer')) {
  let jsDiv = document.getElementById('jsContainer')
  this._renderer2.removeChild(this._document.body, jsDiv);
}

And also this还有这个

this._renderer2.removeChild(this.elementRef.nativeElement, this.script);

But none of them are working.但他们都没有工作。 Any idea of how to destroy the element dynamically?关于如何动态销毁元素的任何想法?

removeChild() expects the first parameter to be the parent node of the node you're trying to remove: https://angular.io/api/core/Renderer2#removechild removeChild()期望第一个参数是您要删除的节点的父节点: https://angular.io/api/core/Renderer2#removechild

Since your're appending the element to jsDiv :由于您要将元素附加到jsDiv

this._renderer2.appendChild(jsDiv,script);

you need to remove it from jsDiv as well:您还需要将其从jsDiv中删除:

let jsDiv = document.getElementById('jsContainer')
this._renderer2.removeChild(jsDiv, this.script);

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

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