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

139
Visualizações
Add click event on element still not in dom

I have to add click event on a anchor element that can load later I know in javascript I can do like this.

document.addEventListener('click', function(e){
    if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
         //do something
    }
});

But I need to do In Typescript in angular and I am trying like this,

 document.addEventListener("click", function (e) {
        try {
        let id = e.target && (e.target as HTMLAnchorElement).id;
        console.log(id)
        if (id == 'lnkCheck') {
          alert('Hi');
        }
        } catch (error) {
          
        }
        

      })

But its not working, also How can I check if the target is an anchor tag

any help, highly appreciated,

UPDATE

the above code is working only issue was I was clicking on wrong place

Thanks

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

0

If you are sure that element will be in the DOM with given id then this thing can be implemented with the help of AfterViewInit interface in the component something like this.

  import { Component, OnInit, AfterViewInit } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
     
    })
    export class AppComponent implements OnInit, AfterViewInit {
  
      constructor() {}
    
      ngOnInit() {
      }
    
      ngAfterViewInit() {
        document.addEventListener('click', function (e) {
          try {
            let id = e.target && (e.target as HTMLAnchorElement).id;
            console.log(id);
            if (id == 'lnkCheck') {
              alert('Hi');
            }
          } catch (error) {}
        });
      }
    }
about 4 years ago · Juan Pablo Isaza Relatório

0

document.addEventListener("click", function (e) {
    const target = e.target;
    if (target instanceof HTMLElement) {
        if (target.tagName === 'A' && target.id === 'lnkCheck') {
            alert('Hi');
        }
    }
})

Is this what you want?

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