Home > Net >  Angular: Create new columns based on 9-record data set
Angular: Create new columns based on 9-record data set

Time:01-18

I have a data set returned from a service call that returns 9 records ONLY. Each record has 2 simple values; the name and value. Here's what an example record looks like.

{
    name: 'item name 1',
    value: 3
}

Instead of listing out a new table row for all 9 records -- where each is only 2 columns, I want to add more columns instead and really fill that table out.

I only want 3 table rows total. I'm trying but right now I've got the new row for each record:

<table>
    <tbody>
        <ng-container *ngFor="let record of dataRecords: let idx=index">
            <tr>
                <td>{{record.name}}</td>
                </td>{{record.value}}</td>
            </tr>
        </ng-container>
    </tbody>
</table>

CodePudding user response:

You can turn your dataset into an array and iterate through it:

    [ 
        [dataRecords[0], [dataRecords[1], [dataRecords[2] ],
        [dataRecords[3], [dataRecords[4], [dataRecords[5] ],
        [dataRecords[6], [dataRecords[7], [dataRecords[8] ],
    ] 

Using a method to generate the formatted array

function formatedDataRecords() {
    var formatedDataRecords = [];
    for(var i = 0; i < this.dataRecords.length; i  = 3) {
        formatedDataRecords.push(array.slice(i, i   3));
    }
    return formatedDataRecords;
}

In the template it would look like this

<table>
    <tbody>
        <ng-container *ngFor="let records of formatedDataRecords(): let idx=index">
            <tr>
                 <ng-container *ngFor="let record of records">
                     <td>{{record.name}}</td>
                     <td>{{record.value}}</td>
                 </ng-container>
            </tr>
        </ng-container>
    </tbody>
</table>

  • Related