Home > OS >  Add click event on element still not in dom
Add click event on element still not in dom

Time:03-15

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

CodePudding user response:

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

CodePudding user response:

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?

  • Related