How to bind event listener for rendered elements in Angular 2?

AngularAddeventlistenerEvent Binding

Angular Problem Overview


How can I bind an event listener in rendered elements in Angular 2?

I am using Dragula drag and drop library. It creates dynamic HTML but my event is not bound to dynamic HTML elements.

Angular Solutions


Solution 1 - Angular

import { AfterViewInit, Component, ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('my-element')
                                .addEventListener('click', this.onClick.bind(this));
}

onClick(event) {
  console.log(event);
}

Solution 2 - Angular

In order to add an EventListener to an element in angular 2+, we can use the method listen of the Renderer2 service (Renderer is deprecated, so use Renderer2):

>listen(target: 'window'|'document'|'body'|any, eventName: string, callback: (event: any) => boolean | void): () => void

Example:

export class ListenDemo implements AfterViewInit { 
   @ViewChild('testElement') 
   private testElement: ElementRef;
   globalInstance: any;       

   constructor(private renderer: Renderer2) {
   }

   ngAfterViewInit() {
       this.globalInstance = this.renderer.listen(this.testElement.nativeElement, 'click', () => {
           this.renderer.setStyle(this.testElement.nativeElement, 'color', 'green');
       });
    }
}

Note:

When you use this method to add an event listener to an element in the dom, you should remove this event listener when the component is destroyed

You can do that this way:

ngOnDestroy() {
  this.globalInstance();
}

The way of use of ElementRef in this method should not expose your angular application to a security risk. for more on this referrer to ElementRef security risk angular 2

Solution 3 - Angular

HostListener should be the proper way to bind event into your component:

@Component({
  selector: 'your-element'
})

export class YourElement {
  @HostListener('click', ['$event']) onClick(event) {
     console.log('component is clicked');
     console.log(event);
  }
}

Solution 4 - Angular

If you want to bind an event like 'click' for all the elements having same class in the rendered DOM element then you can set up an event listener by using following parts of the code in components.ts file.

import { Component, OnInit, Renderer, ElementRef} from '@angular/core';

constructor( elementRef: ElementRef, renderer: Renderer) {
    dragulaService.drop.subscribe((value) => {
      this.onDrop(value.slice(1));
    });
}

public onDrop(args) {

  let [e, el] = args;

  this.toggleClassComTitle(e,'checked');

}


public toggleClassComTitle(el: any, name: string) {

    el.querySelectorAll('.com-item-title-anchor').forEach( function ( item ) {

      item.addEventListener('click', function(event) {
              console.log("item-clicked");

       });
    });

}

Solution 5 - Angular

@HostListener('window:click', ['$event']) onClick(event){ }

check this below link to detect CapsLock on click, keyup and keydown on current window. No need to add any event in html doc

https://stackoverflow.com/questions/45035330/detect-and-warn-users-about-caps-lock-is-on/55476822#55476822

Solution 6 - Angular

import { Component, OnInit } from '@angular/core';

create variable inside the component:

onlineStatus: any; 

inside the ngOnInit() lifecycle method, you can write what you like and it will be treated like a normal JS canvas

  ngOnInit(): void {
    const updateNetworkStatus = () => {
      const text = window.navigator.onLine ? '🟢 online' : '🟥 offline'
      this.onlineStatus = text
    }
    
    updateNetworkStatus()
    window.addEventListener('offline', updateNetworkStatus)
    window.addEventListener('online', updateNetworkStatus)
  }

Here is video on how to do it: https://youtu.be/ENw2AL3gCUw

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSudhanshu sharmaView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularHDJEMAIView Answer on Stackoverflow
Solution 3 - AngularHans TionoView Answer on Stackoverflow
Solution 4 - AngularSagar AroraView Answer on Stackoverflow
Solution 5 - AngularGopala raja naikaView Answer on Stackoverflow
Solution 6 - AngularfruitloafView Answer on Stackoverflow