Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular: EventEmitter is undefined in embedded component

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 game

and 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: error

Note that this is a window and not a component. What I'm doing wrong?

like image 665
Buda Gavril Avatar asked Feb 17 '26 23:02

Buda Gavril


1 Answers

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.

like image 93
kshetline Avatar answered Feb 20 '26 13:02

kshetline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!