I'm learning angular and I have a problem: I have a component inside the main component and I want to emit an event, but I'm getting an error. Here is my code:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-game-control',
templateUrl: './game-control.component.html',
styleUrls: ['./game-control.component.css']
})
export class GameControlComponent implements OnInit {
@Output() numberGenerated: EventEmitter<{v: number}> = new EventEmitter<{v: number}>();
game: any;
constructor() { }
ngOnInit() {
}
startGame() {
this.game = setInterval(this.generateEvent, 1000);
}
stopGame() {
clearInterval(this.game);
}
generateEvent(): void {
const n = Math.floor((Math.random() * 10) + 1);
this.numberGenerated.emit({v: 3});
console.log('event sent');
}
}
this is the html code for this component:
start game end gameand here is the app-rootcomponent html:
<div>
<app-game-control (numberGenerated)="numberGeneratedEvent($event)">
</app-game-control>
<hr>
<br>
</div>
but when I click the button "start game", I'm getting the error from the attached image:

Note that this is a window and not a component. What I'm doing wrong?
Try this instead:
this.game = setInterval(() => this.generateEvent(), 1000);
That might seem like an unnecessary extra layer of function calling, but it's important for the way the this context is maintained.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With