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

前端 未结 5 837
一整个雨季
一整个雨季 2020-12-02 10:16

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 dy

5条回答
  •  悲&欢浪女
    2020-12-02 10:56

    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

提交回复
热议问题