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.
To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
The $event object often contains information the method needs, such as a user's name or an image URL. The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.
You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
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); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With