Reputation: 805
I have fetched data from backend API, need to loop the data in front end but its value not return.
here is my response from backend API.
[
[
{
"choice": 1,
"count": 4,
"percentageValue": "80.0000"
},
{
"choice": 2,
"count": 1,
"percentageValue": "20.0000"
}
],
[
{
"choice": 1,
"count": 4,
"percentageValue": "80.0000"
},
{
"choice": 2,
"count": 1,
"percentageValue": "20.0000"
}
]
]
In ts file
submitPoll(data){
this.pollService.submitPoll(data).subscribe(response =>{
this.percentage=response.body;
});
}
In html file
<p *ngFor="let percentage of percentage;let i= index;">
{{percentage.choice }}
</p>
how to use the for loop for array object ? i need to display the percentage in options
Upvotes: 0
Views: 848
Reputation: 1946
Assuming response.body is a valid json array as specified you could just use the following to grab the inner items and merge them into a new array for use
const percentages = [].concat(...response.body);
You will then end up with the following for use in your loop
[
{
"choice": 1,
"count": 4,
"percentageValue": "80.0000"
},
{
"choice": 2,
"count": 1,
"percentageValue": "20.0000"
},
{
"choice": 1,
"count": 4,
"percentageValue": "80.0000"
},
{
"choice": 2,
"count": 1,
"percentageValue": "20.0000"
}
]
Upvotes: 1
Reputation: 1621
<ng-template ngFor let-percentItems [ngForOf]="percentage">
<ng-template ngFor let-items [ngForOf]="percentItems">
{{ items.choice}} | {{ items.count}} | {{ items.percentageValue}} |<br />
</ng-template>
</ng-template>
OUTPUT
Upvotes: 1
Reputation: 4182
As @MichaelD mentioned, percentage
is array of array. A simple solution is to use *ngFor
twice.
<div *ngFor="let innerArray of percentage;">
<p *ngFor="let obj of innerArray;">
{{obj.choice}}
</p>
</div>
Upvotes: 1