How to display a table with 3 columns in HTML template using a array of strings with Angular?

Viewed 821

I get data in the form of array [ 'one', 'two', 'three', 'four', 'five', 'six'] I want to display it in tabular format as follows,

    <table>
    <caption> Numbers:</caption>
    <tr>
        <td>one</td>
        <td>two</td>
        <td>three</td>
    </tr>
    <tr>
        <td>four</td>
        <td>five</td>
        <td>six</td>
    </tr>
    </table>

Can above template dynamically generated using ngFor & ngIf?

So at each ( index % 3 ) = 0 we will draw new row but how do we do that in HTML with angular directives?

The trick here is the incoming array may have any random number of strings.

2 Answers
<table>
    <caption> Numbers:</caption>
    <ng-container *ngFor="let item of items; let i=index;">
        <tr *ngIf="i % 3 == 0">
            <ng-container *ngFor="let pos of [1, 2, 3]">
                <td *ngIf="i+pos < items.length">{{items[i+pos]}}</td>
            </ng-container>
        </tr>
    </ng-container>
</table>

I haven't tested this, but it should do it.

Try this (TS file):

  data = ['one', 'two', 'three', 'four', 'five', 'six'];
  results: any[] = [];

  constructor() {
    this.results = this.groupColumns(this.data);
  }

  groupColumns(arrays) {
    const newRows = [];
    for (let index = 0; index < arrays.length; index += 3) {
      newRows.push(arrays.slice(index, index + 3));
    }
    return newRows;
  }

in HTML:

<table>
    <caption> Numbers:</caption>
    <tr *ngFor="let result of results">
        <td>{{result[0]}}</td>
        <td>{{result[1]}}</td>
        <td>{{result[2]}}</td>
    </tr>
</table>

Working Demo

Related