I am learning Angular (version 12.0.1, TypeScript 4.3.4) and cannot figure out why this event emitter is undefined. Any ideas?
The error message I get: ERROR TypeError: this.gameClick is undefined
.ts file:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-game-control',
templateUrl: './game-control.component.html',
styleUrls: ['./game-control.component.scss']
})
export class GameControlComponent implements OnInit {
gameInterval: number = 0;
score: number = 0;
@Output() gameClick: EventEmitter<any> = new EventEmitter<{ clicks: number }>();
constructor() { }
ngOnInit(): void {
}
emitEvent() {
this.gameClick.emit({ clicks: this.score });
this.score++;
}
startGame() {
this.gameInterval = setInterval(this.emitEvent, 1000);
}
stopGame() {
clearInterval(this.gameInterval);
}
}
html file:
<div class="controls">
<button
class="btn-game"
(click)="startGame()"
>Start game</button>
<button
class="btn-game"
(click)="stopGame()"
>Stop game</button>
</div>
Change this function:
emitEvent() {
this.gameClick.emit({ clicks: this.score });
this.score++;
}
to
emitEvent = (): void => {
this.gameClick.emit({ clicks: this.score });
this.score++;
}