less than 1 minute read

Bind local method to Dom event listener

Lets say you have a method called which you want to be called on some event.

Method 1

You can add the event listener and while adding you should bind this event with this :D

  localTypescriptMethod() {
    console.log('hi :)');
  }

  addClick() {
    window.addEventListener('click', this.localTypescriptMethod.bind(this));
  }

Method 2

Use HostListener to bind the method to the click event, or some other event.

@HostListener('document:click')
  localTypescriptMethod() {
    console.log('hi :)');
  }

Leave a comment