CH4B
CH4B

Reputation: 774

(Angular) Using *ngFor to fill table

I need a table structure somewhat like this:

enter image description here

For that, I'm using basic Bootstrap's table and the Angular's *ngFor. Each table cell is filled by a different name, coming from a back-end array.
This is how I'm doing it:

<table class="table">
    <tbody>
      <tr *ngFor="let data of User;" class={{data.nome}} id='Check_{{data.id}}'
        (click)='toggleCheckbox($event.target)'>
        <td>{{data.nome}}</td>
        <td>{{data.nome}}</td>
      </tr>
    </tbody>
</table>

The structure works fine, but the cells are not filled like I wanted. Each row is filled with the same name like this:

enter image description here

and I understand that this happens beacuse the ngFor is looping after the row changes, not for each new cell. The problem is that I can't fill the table correctly, and if I do, I can't keep the table's structure intact.
Is there a better way to achieve this? Using either Bootstrap or HTML5 is fine.
I believe the main problem here (and why I could not find a fitting answer online) is because I don't know the size of the array, so the size of this table is variable, for each, it will fill new cell while it still follows the structure.

Upvotes: 1

Views: 6605

Answers (1)

Nirali
Nirali

Reputation: 514

you can create odd even filter like given here in answer

Angular 2 ngFor over even/odd items

and then use in your html like below

<table class="table">
    <tbody>
<ng-container *ngFor="let data of User | evenodd:'odd'">
      <tr class={{data.nome}} id='Check_{{data.id}}'
        (click)='toggleCheckbox($event.target)'>
        <td>{{data.nome}}</td>
      </tr>
</ng-container>
<ng-container *ngFor="let data of User | evenodd:'even'">
    <tr class={{data.nome}} id='Check_{{data.id}}'
        (click)='toggleCheckbox($event.target)'>
        <td>{{data.nome}}</td>
      </tr>
</ng-container>
    </tbody>
</table>

Upvotes: 1

Related Questions