Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating in form of table in angular

Tags:

angular

I am trying to iterate the list in form of table. The following list should be rendered in the form of table using *ngFor:

I/p :

let list = [
  {
    "key1": {
      "subkey1": [
        1,
        2,
        3,
        1
      ],
      "subkey2": [
        3,
        2,
        3,
        4
      ]
    }
  },
  {
    "key2": {
      "subkey1": [
        1
      ],
      "subkey2": [
        0
      ]
    }
  }
]

Table format (This is how table should render) :

Categories | subkey1 | subkey2

key1       | 1,2,3,1 | 3,2,3,4

key2       |  1      |  0

I tried but its wrong :

Code I tried to iterate in component.html :

 <table border="1">
      <thead>
          <tr>
              <th>Categories</th>
              <th *ngFor="let each of categoriesHeading"> {{each}} </th>  // Array of subkeys
            </tr>
      </thead>
      <tbody *ngFor="let each of categoriesList">
        <tr>
          <td *ngFor="let key of objectKeys(each)">// iterating keys
              {{key}} 
          </td>
          <td> </td> // I don't know how to itereate the values of each subkey of key [1,2,3]
        </tr>
      </tbody>
    </table>

I was not able to share StackBlitz. So I'm sharing this screenshot : enter image description here

Please let me know if something is missing.

like image 848
Kedar Kulkarni Avatar asked Oct 16 '22 10:10

Kedar Kulkarni


1 Answers

You can arrange the data as required and then display it in template.

Try like this:

Working Demo

Controller:

  categoriesHeading = [];
  displayData = [];

  constructor() {
    this.categoriesHeading = Object.keys(this.list[0].key1);

    this.list.forEach(item => {
      let obj = {};
      obj["key"] = Object.keys(item)[0];
      Object.keys(item[Object.keys(item)[0]]).forEach((subkey, i) => {
        obj[subkey] = item[Object.keys(item)[0]][subkey].join();
      });
      this.displayData.push(obj);
    });
  }

Template:

<table border="1">
    <thead>
        <tr>
            <th>Categories</th>
            <th *ngFor="let each of categoriesHeading"> {{each}} </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of displayData">
            <td *ngFor="let each of item | keyvalue"> {{each.value}} </td>
        </tr>
    </tbody>
</table>

NOTE: For Angular 4, if you don't want to use (keyvalue pipe), then do the following.

TS:

objectKeys = Object.keys;

Template:

<table border="1">
    <thead>
        <tr>
            <th>Categories</th>
            <th *ngFor="let each of categoriesHeading"> {{each}} </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of displayData">
            <td *ngFor="let key of objectKeys(item)"> {{item[key]}} </td>
        </tr>
    </tbody>
</table>
like image 105
Adrita Sharma Avatar answered Nov 11 '22 04:11

Adrita Sharma