Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!