Eliemerson Fonseca
Eliemerson Fonseca

Reputation: 757

Populate table with one array inside another array *ngFor

I need a popular table to compare two products. The model of my json contains an array inside the other. In this way.

products: [
  {
    nome: 'Product Basic',
    preco: 9.90,
    categoria: 1,
    caracteristicas: [
      '1 basic',
      '2 basic',
      '3 basic',
      '4 basic',
      '5 basic',
      '6 basic]
  },
  {
    nome: 'Product Plus',
    preco: 14.90,
    categoria: 1,
    caracteristicas: [
      '1 Plus',
      '2 Plus',
      '3 Plus',
      '4 Plus',
      '5 Plus',
      '6 Plus']
  }
]

I am creating the table this way

   <tr *ngFor="let columnCaracteristica of tableComparative.columns">
        <td>{{columnCaracteristica}}</td>
        <ng-container *ngFor="let produto of tableComparative.produtos">
            <td *ngFor="let caracteristica of produto.caracteristicas">{{caracteristica}}</td>
        </ng-container>
    </tr>

Feature to be compared

columns: ['Agencia', 'Encandor', 'Roubo', 'Vale presente', 'Raios', 'Fogo'],

Result enter image description here

Expected

enter image description here

Upvotes: 2

Views: 296

Answers (1)

yurzui
yurzui

Reputation: 214007

You may do that by the following template

<table *ngIf="products?.length">
  <tr *ngFor="let characteristic of products[0].caracteristicas; let i = index">
    <td>
      {{ columns[i]}}
    </td>
    <td *ngFor="let product of products">
      {{ product.caracteristicas[i] }}
    </td>
  </tr>
</table>

Ng-run Example

Moreover, you can also add top header to display product names if you want

<thead>
  <tr>
    <th></th>
    <th *ngFor="let product of products">
      {{ product.name }}
    </th>
  </tr>
</thead>

Ng-run Example

enter image description here

Upvotes: 1

Related Questions