You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular骰子游戏开发:如何实现更新后骰子值的浏览器显示?

问题分析与解决方案

你遇到的核心问题是:子组件app-dice-roll没有接收父组件更新后的骰子数值。虽然你已经成功将掷骰子的结果传递到父组件并更新了diceValues数组,但子组件不知道要显示这个数组里的内容——因为你没有给子组件定义用于接收数据的输入属性,所以模板里的{{ diceValue }}没有数据来源,自然无法在浏览器中显示。

下面是具体的修复步骤:

1. 给子组件添加输入属性

在dice-roll.component.ts中,添加@Input()装饰器来声明一个接收父组件数据的属性:

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 {
 @Input() diceValue: number = 0; // 新增:定义输入属性,用于接收父组件传递的骰子值
 @Output() onRoll: EventEmitter<number> = new EventEmitter();

 diceRoller() {
 setTimeout(() => {
 this.onRoll.emit(Math.floor(Math.random() * 6) + 1);
 }, 750);
 };
}

2. 在父组件模板中绑定输入属性

修改dice-game.component.html,在循环渲染的app-dice-roll标签上,把父组件diceValues数组中对应索引的值传递给子组件的diceValue输入属性:

<div>
 <app-dice-roll 
  *ngFor="let diceValue of diceValues; let i = index" 
  [diceValue]="diceValues[i]" <!-- 新增:绑定输入属性,传递最新的骰子值 -->
  (onRoll)="update(i, $event)"
 ></app-dice-roll>
</div>

为什么这样能解决问题?

  • 当你点击掷骰子按钮时,子组件通过EventEmitter把随机数传递给父组件的update方法,父组件更新diceValues数组中对应索引的值
  • 通过@Input绑定,父组件的diceValues数组更新后,Angular会自动把最新的值同步到子组件的diceValue属性上
  • 子组件模板里的{{ diceValue }}现在有了正确的数据来源,就能在浏览器中显示出掷出的骰子数了

额外优化建议

如果不想初始显示0,可以在子组件模板里加个简单判断:

<div class="dice-roll">
 <span>{{ diceValue > 0 ? diceValue : '' }}</span>
</div>
<button type="button" id="roll-button" (click)="diceRoller()">Roll!</button>

内容的提问来源于stack exchange,提问作者Hannah Matthewson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:48:39