Home > Blockchain >  Angulat emit does not work on addEventListener
Angulat emit does not work on addEventListener

Time:10-26

I am trapping an event in my ngAfterViewInit as below.

ngAfterViewInit() {
    window.addEventListener("resize", this.resetWindowHeight);
}

resetWindowHeight(){
    const element: HTMLIFrameElement = document.getElementById('frame') as HTMLIFrameElement;
    if (element) {
       this.onHeightChange.emit()  /// Error here
    }
}

When I try to emit an event, I get an error 'Cannot read properties of undefined (reading 'emit')'. How can I solve this? I want to emit when the user resizes the window

CodePudding user response:

The way the resetWindowHeight is associated causes this error. This is the scope resolution issue behind the need for arrow functions.

ngAfterViewInit() {
    // You can also make () => this.resetWindowHeight()
    window.addEventListener("resize", this.resetWindowHeight.bind(this));
}
  • Related