Saswat
Saswat

Reputation: 12836

How to display value of a key dynamically in Angular2?

I am getting a JSON response like this:-

{
  "status": 1,
  "message": "Data found",
  "list": [
    {
      "id": "1",
      "title": "First Data"
    },
    {
      "id": "2",
      "title": "Second Data"
    }
  ],
  "total": 3,
  "current_page": "1",
  "error": 0
}

In the component file, I am storing the list obj like this:-

viewPage(page,per_page){  
  this._adminPage.fetchAdminPageData(page, per_page).subscribe(
      data => {
            this.list = data.list;
            this.total_item = data.total;
            this.current_page = data.current_page;
            this.arrayOfKeys = Object.keys(this.list[0]);
          },
      err => {
            console.log(err)
          },
      () => {}
    ); 
  this.status = true;       
}

Using the this.arrayOfKeys = Object.keys(this.list[0]); I am getting the keys of list.

In the template page, I am writing the following code:-

<thead>
  <tr>
     <th *ngFor='let key of arrayOfKeys'>{{key}}</th>
  </tr>
</thead>

This displays id and title in the table headers. I am doing this to make the whole table dynamic.

Now, I want the values of each row would be listed by a looping through each object.

So I am trying to write something like this:-

<table class="table table-striped table-bordered responsive">
   <thead>
      <tr>
        <th *ngFor='let key of arrayOfKeys'>{{key}}</th>
      </tr>
   </thead>
   <tbody>
      <tr *ngFor='let items of list'>
        <td *ngFor='let key1 of arrayOfKeys'>[value of that key of that row]</td>
      </tr>
   </tbody>
</table>

{{items.id}} displays value of id like 1, 2. I want something like {{items.{{key1}} to display the value of each key, like 1 or First Data. How can I do this?

Upvotes: 0

Views: 357

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68655

You need to use [] notation for it.

<tr *ngFor='let items of list'>
   <td *ngFor='let key1 of arrayOfKeys'>{{ items[key1] }}</td>
</tr>

Upvotes: 1

Related Questions