首页 文章

angular:在嵌入式组件中未定义EventEmitter

提问于
浏览
1

我正在学习角度,我遇到了一个问题:我在主要组件中有一个组件,我想发出一个事件,但是我收到了一个错误 . 这是我的代码:

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');
  }
}

这是该组件的html代码:
开始游戏结束游戏
这是app-rootcomponent html:

<div>
    <app-game-control (numberGenerated)="numberGeneratedEvent($event)">
    </app-game-control>
    <hr>
    <br>
</div>

但当我单击按钮"start game"时,我从附加图像中收到错误:
error

请注意,这是一个窗口而不是组件 . 我做错了什么?

1 回答

  • 0

    试试这个:

    this.game = setInterval(() => this.generateEvent(), 1000);
    

    这似乎是一个不必要的额外功能调用层,但它对于维护 this 上下文的方式很重要 .

相关问题