VSO VSO -4 years ago 93
TypeScript Question

Angular 2 - Run Component Method from Component's Constructor?

constructor() {

document.addEventListener('someEvent', function(event) {
console.log(event.data);
this.test(); //throws error - this.test() is undefined
});
}


If I move it to
ngOnInit
, it works fine:

ngOnInit() {
this.test(); //works ok
}


The function is just a method on the component, defined after the constructor:

public test(){
console.log('TEST');
}


My end goal is to run the
test()
method of my component every time
someEvent
event fires on the global window (the event comes from raw javascript, i.e.
document.dispatchEvent(event, {'detail': evntPayload});


How do I accomplish this?

Answer Source

Use arrow functions to keep this pointing to the current class instance

  constructor() {

    document.addEventListener('someEvent', (event) => { // <<< changed
      console.log(event.data);
      this.test(); //throws error - this.test() is undefined
    });
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download