简体   繁体   中英

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

You could do this by using the approach of this stackoverflow post: How to display json object using *ngFor

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.

If you are using angular 6.1 or greater you can use keyValue pipe

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

<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.

Pipe Implementation: https://stackblitz.com/edit/ionic-xvt2ha
OutPut : https://ionic-xvt2ha.stackblitz.io

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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