我如何创建一个成角度的骰子滚轮以为每个骰子显示不同的数字?

问题描述 投票:0回答:1

我是Angular和Typescript的新手。我想创建一个骰子应用程序,但不确定如何创建显示1-6之间数字的6个不同骰子。

我创建了6个骰子,此刻显示1-6之间的数字。但是每个骰子上的数字都相同,我想知道如何显示不同的数字。但是,同一卷上的数字可以出现多次。例如。 3、5、1、3、6、6。

我了解下面的HTML中显示的{{diceValue}}将显示相同的数字,因为它设置为等于一个值,然后重复了6次。但是我不确定如何更新它以显示6个单独的值。

// HTML 

<div class="diceRoller">
    <div>
        <div class="square">
            <span>{{ diceValue }}</span>
        </div>
        <div class="square">
            <span>{{ diceValue }}</span>
        </div>
        <div class="square">
            <span>{{ diceValue }}</span>
        </div>
        <div class="square">
            <span>{{ diceValue }}</span>
        </div>
        <div class="square">
            <span>{{ diceValue }}</span>
        </div>
        <div class="square">
            <span>{{ diceValue }}</span>
        </div>
    </div>
    <button type="button" id="roll-button" (click)="diceRoll()">Roll Dice!</button>
</div>

// Angular: dice-roll.component.ts

export class DiceRollComponent {
    public diceValue: number = 0;

    diceRoll() {
        let randomNum = Math.floor(Math.random() * 6) + 1;
        this.diceValue = randomNum;
    }
}
angular typescript
1个回答
0
投票

尝试一下:

// HTML 

<div class="diceRoller">
    <div>
        <div class="square" *ngFor="let diceValue of diceValues">
            <span>{{ diceValue }}</span>
        </div>
    </div>
    <button type="button" id="roll-button" (click)="diceRoll()">Roll Dice!</button>
</div>

// Angular: dice-roll.component.ts

export class DiceRollComponent {
  public diceValues: Array<number> = [0, 0 ,0 ,0 ,0 ,0];

  diceRoll() {
    for (let i = 0; i < this.diceValues.length; i++) {
      this.diceValues[i] = Math.floor(Math.random() * 6) + 1;
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.