gpt4 book ai didi

javascript - Angular :EventEmitter 在嵌入式组件中未定义

转载 作者:行者123 更新时间:2023-12-02 03:32:42 26 4
gpt4 key购买 nike

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

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>

但是当我点击“开始游戏”按钮时,我从附图中得到了错误: error

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

最佳答案

试试这个:

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

这可能看起来像是一个不必要的额外函数调用层,但它对于 this 上下文的维护方式很重要。

关于javascript - Angular :EventEmitter 在嵌入式组件中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51344481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com