How to bind an event listener for displayed elements in Angular 2?

How to link 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 related to dynamic HTML elements.

+6
source share
3 answers
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); } 
+15
source

If you want to bind an event of type 'click' for all elements that have the same class in the rendered DOM element, you can configure the event listener using the following parts of the code in the 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"); }); }); } 
+2
source

To add an EventListener to an element in angular 4, we can use the listen Renderer2 service method ( 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; constructor(private renderer: Renderer2) { } ngAfterViewInit() { this.renderer.listen(this.testElement.nativeElement, 'click', () => { this.renderer.setStyle(this.testElement.nativeElement, 'color', 'green'); }); } } 
+1
source

Source: https://habr.com/ru/post/1014005/


All Articles