Search code examples
htmlangularangular-directive

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


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.


Solution

  • <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.