简体   繁体   中英

Remove dynamically created element by id in angular component

I've added an external script to a component like so:

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);
}

The script actually loads a live chat widget which is dynamically created in the DOM when the script is loaded.

I'd like to remove the element from the DOM when the component is destroyed but i'm not sure how to create a reference to a dynamically created element.

I've seen examples using elementRef, but this assumes you have control over the element and it isn't dynamically created.

How can i target an element dynamically, similair to using event delegation but in angular?

You can add a #local reference" to a ng-container or a div that contains your element, and then in your code, with @ViewChild link the reference, and finally delete it with:

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

this.yourLocalReferenceHTMLname.nativeElement.remove();

Anyway, try not to use elementRef [From the Angular Documents]:

Use elementRef API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead. Alternatively, you can use Renderer2 , which provides API that can safely be used even when direct access to native elements is not supported.

Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker.

Literally, from this render2 article HERE :

Why not ElementRef?

We can use the nativeElement property of the ElelemtRef to manipulate the DOM.The nativeElement Property contains the reference to the underlying DOM object. This gives us direct access to the DOM, bypassing the Angular.

There is nothing wrong with using it, but it is not advisable for the following reasons:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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