Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading