3

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?

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196

1 Answers1

6

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.

kshetline
  • 12,547
  • 4
  • 37
  • 73