Angular 12:事件发射器未定义
Angular 12: Event emitter is undefined
我正在学习 Angular(版本 12.0.1,TypeScript 4.3.4),无法弄清楚为什么这个事件发射器未定义。有什么想法吗?
我收到的错误消息:错误类型错误:this.gameClick 未定义
.ts 文件:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-game-control',
templateUrl: './game-control.component.html',
styleUrls: ['./game-control.component.scss']
})
export class GameControlComponent implements OnInit {
gameInterval: number = 0;
score: number = 0;
@Output() gameClick: EventEmitter<any> = new EventEmitter<{ clicks: number }>();
constructor() { }
ngOnInit(): void {
}
emitEvent() {
this.gameClick.emit({ clicks: this.score });
this.score++;
}
startGame() {
this.gameInterval = setInterval(this.emitEvent, 1000);
}
stopGame() {
clearInterval(this.gameInterval);
}
}
html 文件:
<div class="controls">
<button
class="btn-game"
(click)="startGame()"
>Start game</button>
<button
class="btn-game"
(click)="stopGame()"
>Stop game</button>
</div>
更改此功能:
emitEvent() {
this.gameClick.emit({ clicks: this.score });
this.score++;
}
至
emitEvent = (): void => {
this.gameClick.emit({ clicks: this.score });
this.score++;
}
我正在学习 Angular(版本 12.0.1,TypeScript 4.3.4),无法弄清楚为什么这个事件发射器未定义。有什么想法吗?
我收到的错误消息:错误类型错误:this.gameClick 未定义
.ts 文件:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-game-control',
templateUrl: './game-control.component.html',
styleUrls: ['./game-control.component.scss']
})
export class GameControlComponent implements OnInit {
gameInterval: number = 0;
score: number = 0;
@Output() gameClick: EventEmitter<any> = new EventEmitter<{ clicks: number }>();
constructor() { }
ngOnInit(): void {
}
emitEvent() {
this.gameClick.emit({ clicks: this.score });
this.score++;
}
startGame() {
this.gameInterval = setInterval(this.emitEvent, 1000);
}
stopGame() {
clearInterval(this.gameInterval);
}
}
html 文件:
<div class="controls">
<button
class="btn-game"
(click)="startGame()"
>Start game</button>
<button
class="btn-game"
(click)="stopGame()"
>Stop game</button>
</div>
更改此功能:
emitEvent() {
this.gameClick.emit({ clicks: this.score });
this.score++;
}
至
emitEvent = (): void => {
this.gameClick.emit({ clicks: this.score });
this.score++;
}