Jigarb1992
Jigarb1992

Reputation: 848

forEach loop in Angular 2

I am working on a project with Angular 2.
In one of my scenario I get the Array from the API call.
Array is like :
[{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}]

Using this Array I want to create the table like

key1 key2 key3
value1 value2 value3
value1 value2 value3
value1 value2 value3


So, my question is how do I get the key and the value from the array

Is there any forEach loop?

Upvotes: 3

Views: 19064

Answers (1)

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

When the data come from your API

You need to create a new KeysArray withe the following code snippet on your component. Assuming each object will hold same keys.

keysArray = Object.keys(this.apiData[0]);

Now iterate the keys array and apiData in your template as follows.

<table>
    <thead>
        <tr>
            <th *ngFor="let key of keysArray; let i = index;">{{key}}</th>
        <tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of apiData;">
            <td *ngFor="let key of keysArray;">{{item[key]}}</td>
        <tr>
    </tbody>
</table>

Upvotes: 3

Related Questions