Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda