angulartypescriptangular-decorator

emitting event multiple times in angular gives error cannot read properties of undefined "(reading) emit"


I have an event binding on button (click)="onStart()". It emits the event this.numEmitter for the first time in setInterval after that it gives the error ERROR TypeError: Cannot read properties of undefined (reading 'emit')

    incNum: number;
    timer: number;
    @Output() numEmitter: EventEmitter<number> = new EventEmitter();

    constructor() {
        this.timer = -1;
        this.incNum = 0;
    }

    
    onStart() {
        this.timer = window.setInterval(function () {
            this.incNum++;
            this.numEmitter.emit(this.incNum);
        }, 1000);
    }

    onStop() {
        window.clearInterval(this.timer);
    }

Can anybody please tell me what's the issue and how to fix it?


Solution

  • The problem is that the handler you provided does not capture the right this. Try using an arrow function instead:

    onStart() {
      this.timer = window.setInterval(() => {
        this.incNum++;
        this.numEmitter.emit(this.incNum);
      }, 1000);
    }
    
    onStop() {
      window.clearInterval(this.timer);
    }