I am trying to to loop through an Object in Angular with NgFor.
ngOnInit() {
this.service.getConveyors()
.subscribe(response => {
this.conveyors = response;
this.conveyorsArray = Object.keys(this.conveyors.data.conveyor);
});
The html looks like this:
<div *ngFor="let item of conveyorsArray | keyvalue">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>
The data I get from api looks like the picture below.
My output:
Key: 0 and Value: 0
Key: 1 and Value: 1
Key: 2 and Value: 2
Key: 3 and Value: 3
Key: 4 and Value: 4
I want to display all conveyors.
CodePudding user response:
You should not use object.keys in your component so it should be
this.conveyorsArray = this.conveyors.data.conveyor;
instead of
this.conveyorsArray = Object.keys(this.conveyors.data.conveyor);
Then on UI loop through your array first and then use keyvalue pipe on the object instead of array
<div *ngFor="let arrayitem of conveyorsArray">
<div *ngFor="let item of arrayitem | keyvalue">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>
</div>