0

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?

1 Answers1

1

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);
}
Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29