我正在开发骰子游戏应用程序,最近我对应用程序进行了重组,以拆分出各个组件,以便每个组件都具有特定的功能。目前,我正在使用掷骰子组件,使用@Output和EventEmitter将我的事件(单击按钮掷骰子)传递到我的骰子游戏组件,在此我希望它显示每个值。
该事件之所以有效,是因为当我在骰子游戏组件的“更新”功能中执行console.log(newValue)时,我在控制台中得到一个介于1到6之间的数字。但是我似乎无法获得此数字在浏览器中显示的值。
理想情况下,该值将传递到我的dice-roll.component.html文件中,在此文件中我可以在span标签之间显示该值。然后,该值将在浏览器中可见,因为我已经将标签添加到了dice-game.component.html。
任何帮助将不胜感激。谢谢!
dice-game.component.html:
<div>
<app-dice-roll *ngFor="let diceValue of diceValues; let i = index" (onRoll)="update(i, $event)"></app-dice-roll>
</div>
dice-game.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-dice-game',
templateUrl: 'dice-game.component.html',
styleUrls: ['dice-game.component.css']
})
export class DiceGameComponent {
diceValues: Array<number> = [0, 0, 0, 0, 0];
update(i, newValue) {
this.diceValues[i] = newValue;
console.log(newValue);
}
}
dice-roll.component.html:
<div class="dice-roll">
<span>{{ diceValue }}</span>
</div>
<button type="button" id="roll-button" (click)="diceRoller()">Roll!</button>
dice-roll.component.ts:
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-dice-roll',
templateUrl: 'dice-roll.component.html',
styleUrls: ['dice-roll.component.css']
})
export class DiceRollComponent {
@Output()
onRoll: EventEmitter<number> = new EventEmitter();
diceRoller() {
setTimeout(() => {
this.onRoll.emit(Math.floor(Math.random() * 6) + 1);
}, 750);
};
}
答案 0 :(得分:1)
如果要在dice-roll组件(子组件)中显示新的diceValue,则需要通过在此dice-roll组件中创建@Input()属性将该值传递给dice-roll组件。
@Component({
selector: 'app-dice-roll',
templateUrl: 'dice-roll.component.html',
styleUrls: ['dice-roll.component.css']
})
export class DiceRollComponent {
@Input() diceValue: number;
@Output() onRoll: EventEmitter<number> = new EventEmitter();
...
}
然后您可以通过以下代码将值从骰子游戏组件(父组件)传递到骰子掷骰子组件(子组件):
在HTML中:
<div>
<app-dice-roll *ngFor="let diceValue of diceValues; let i = index"
[diceValue]="diceValue" (onRoll)="update(i, $event)"></app-dice-roll>
</div>
答案 1 :(得分:0)
in .ts =>
diceValue:int = 0
rollDice() {
this.diceValue = (Math.floor(Math.random() * 6) + 1)
}
in .html =>
<button (click)="rollDice()"> Roll that dice! </button>
<h2>dice value is: {{diceValue}}</h2>