Dynamically add event listener

前端 未结 4 803
小鲜肉
小鲜肉 2020-11-22 10:21

I am just starting to mess around with Angular 2 and I wonder if anyone can tell me the best way to dynamically add and remove event listeners from elements.

I have

4条回答
  •  无人及你
    2020-11-22 10:54

    I will add a StackBlitz example and a comment to the answer from @tahiche.

    The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy method.

    I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?

    export class MyComponent implements OnInit, OnDestroy {
    
      public removeEventListener: () => void;
    
      constructor(
        private renderer: Renderer2, 
        private elementRef: ElementRef
      ) {
      }
    
      public ngOnInit() {
        this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
          if (event.target instanceof HTMLAnchorElement) {
            // Prevent opening anchors the default way
            event.preventDefault();
            // Your custom anchor click event handler
            this.handleAnchorClick(event);
          }
        });
      }
    
      public ngOnDestroy() {
        this.removeEventListener();
      }
    }
    

    You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.

    I added a body with an image as follows:


    to show that the sanitizer is doing its job.

    Here in this fiddle you find the same body attached to an innerHTML without sanitizing it and it will demonstrate the issue.

提交回复
热议问题