简体   繁体   English

在Angular4视图中显示对象

[英]Display objects in the view Angular4

   { player0: {select_by: "player_id", i: 107993, role: "main", team: "team1"}
    player1: {select_by: "player_id", i: 108322, role: "main", team: "team1"}
    player2: {select_by: "player_id", i: 107995, role: "main", team: "team1"}
    player3: {select_by: "player_id", i: 108033, role: "main", team: "team1"}
    player4: {select_by: "player_id", i: 108866, role: "main", team: "team1"}
}

How i can display this play of objects in the view ? 我如何在视图中显示对象的播放? ( Ionic3, Angular ) Display role of every player for example (Ionic3,Angular)例如,显示每个玩家的角色

You could do this by using the approach of this stackoverflow post: How to display json object using *ngFor 您可以使用以下stackoverflow帖子的方法来做到这一点: 如何使用* ngFor显示json对象

Another option would be creating a helper array where you put all players in. 另一种选择是创建一个放置所有玩家的助手数组。

@Component({
  selector: "app-selector",
  templateUrl: "your.html",
  styleUrls: ["your.scss"]
})
export class Your-Class implements OnInit {
  public playerArr: Player[];
  ...

  ngOnInit() {
    this.playerArr = [];
    // Iterate your object here named as players and push all players into array
    for(let player in players){
        this.playerArr.push(players[player]);
    }
  }

  ...
}

After rebuilding your json as array you can easily use the *ngFor in your html to loop the array and retrieve your data. 在将json重建为数组之后,您可以轻松地在html中使用*ngFor来循环数组并检索数据。

If you are using angular 6.1 or greater you can use keyValue pipe 如果您使用的是Angle 6.1或更高版本,则可以使用keyValue管道

Try something like this 试试这个

<div *ngFor="let item of playersObject | keyvalue;>{{item.key}} : {{ item.value.role }}</div>

If you want a plain object to load you can use json pipe 如果要加载普通对象,可以使用json管道

<div>{{playerObject | json}}</div>

Hope it works - Happy coding :) 希望它能工作-快乐的编码:)

For your specific question, try: 对于您的特定问题,请尝试:

<div *ngFor="let player of players; let i = index">
   {{ player["player" + i]["role"] }}
<div>

players refers to the object you mentioned above. 玩家指的是您上面提到的对象。

The more better approach will be using pipes. 更好的方法是使用管道。 Refer to this implementation at stackblitz. 请在stackblitz上参考此实现。

Pipe Implementation: https://stackblitz.com/edit/ionic-xvt2ha 管道实施: https//stackblitz.com/edit/ionic-xvt2ha
OutPut : https://ionic-xvt2ha.stackblitz.io 输出: https ://ionic-xvt2ha.stackblitz.io

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM