【问题标题】:Accessing array from another component in Angular从Angular中的另一个组件访问数组
【发布时间】:2019-11-23 12:42:50
【问题描述】:

我有一个在名为“玩家选择”的组件中创建并填充的数组。在另一个名为“游戏”的组件中,我想访问数组并从中添加拉数据。数组由对象组成。每个对象代表一个“玩家”。每个玩家都有一个名字,存储为playerName 属性。我想访问这个属性,以便可以在game.component.html 上显示它。我已尽我所能关注在线文章,但似乎仍然有问题。代码如下:

player-selection.component.ts

@Component({
  selector: "app-player-selection",
  templateUrl: "./player-selection.component.html",
  styleUrls: ["./player-selection.component.css"]
})
export class PlayerSelectionComponent implements OnInit {
  players: PlayerObject[];
  constructor() {}

  ngOnInit() {
    this.players = [];
  }
  addNewPlayer() {
    var element = <HTMLInputElement>document.getElementById("nameInput");
    var nameInput = (<HTMLInputElement>document.getElementById("nameInput"))
      .value;
    var playerObject = new PlayerObject(nameInput);
    this.players.push(playerObject);
    element.value = "";
    console.log(this.players[0].playerName);
  }
}

player-selection.component.html

    ...</div>
</div>
<app-game [playerArr]="players"></app-game>
<router-outlet></router-outlet>

game.component.ts

@Component({
  selector: "app-game",
  templateUrl: "./game.component.html",
  styleUrls: ["./game.component.css"]
})
export class GameComponent implements OnInit {
  @Input() playerArr: PlayerObject[];
  constructor() {}

  ngOnInit() {

  }
}

game.component.html

<mat-tab label="1">
        <div *ngFor="let name of playerArr">
            <h3>{{ name.playerName }}</h3>
            <mat-form-field class="scoreInput">
              <input matInput placeholder="Score" id="player0" />
            </mat-form-field>
        </div>
</mat-tab>

【问题讨论】:

  • 你的问题到底是什么?
  • 你的 console.log 工作正常吗?

标签: angular angular-components


【解决方案1】:

我能够使用数据服务来实现这一点。我在data.service.ts中创建了以下类

export class DataService {
  private playerArray: PlayerObject[];
  // private playerIndex: number = 0;
  constructor() {
    this.playerArray = [];
  }

  addPlayer(player: PlayerObject) {
    this.playerArray.push(player);
    // this.playerIndex++
  }
  returnIndexName(index: number) {
    return this.playerArray[index].playerName;
  }
  playerCount() {
    return this.playerArray.length;
  }
  returnEachPlayerObject() {
    return this.playerArray;
  }
  addToScores(holesArray: number[], index: number) {
    for (var i = 0; i < holesArray.length; i++) {
      this.playerArray[index].scores.push(holesArray[i]);
    }
  }

  totalScores(index: number) {
    return this.playerArray[index].scores.reduce((x, y) => x + y);
  }
}

【讨论】:

    猜你喜欢
    • 2016-09-28
    • 2018-02-20
    • 1970-01-01
    • 2018-07-01
    • 2020-02-22
    • 1970-01-01
    • 2019-09-11
    • 2017-10-10
    • 2020-06-18
    相关资源
    最近更新 更多