Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an ngFor to traverse a 2 dimensional array

I've been beating my head up against the wall on this one for a while but I finally feel close. What I'm trying to do is read my test data, which goes to a two dimensional array, and print its contents to a table in the html, but I can't figure out how to use an ngfor to loop though that dataset

Here is my typescript file

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
    public tableData: any[][];

    constructor(http: Http) {

        http.get('/api/SampleData/DatatableData').subscribe(result => {
            //This is test data only, could dynamically change
            var arr = [
                { ID: 1, Name: "foo", Email: "[email protected]" },
                { ID: 2, Name: "bar", Email: "[email protected]" },
                { ID: 3, Name: "bar", Email: "[email protected]" }
            ]
            var res = arr.map(function (obj) {
                return Object.keys(obj).map(function (key) {
                    return obj[key];
                });
            });

            this.tableData = res;
            console.log("Table Data")
            console.log(this.tableData)
        });
    }
}

Here is my html which does not work at the moment

<p *ngIf="!tableData"><em>Loading...</em></p>

<table class='table' *ngIf="tableData">
    <tbody>
        <tr *ngFor="let data of tableData; let i = index">
            <td>
            {{ tableData[data][i] }}
            </td>

        </tr>
    </tbody>
</table>

Here is the output from my console.log(this.tableData) enter image description here

My goal is to have it formatted like this in the table

1 | foo | [email protected]
2 | bar | [email protected]

Preferably I'd like to not use a model or an interface because the data is dynamic, it could change at any time. Does anyone know how to use the ngfor to loop through a two dimensional array and print its contents in the table?

like image 334
Zach Avatar asked Mar 06 '26 13:03

Zach


1 Answers

Like Marco Luzzara said, you have to use another *ngFor for the nested arrays.

I answer this just to give you a code example:

<table class='table' *ngIf="tableData">
    <tbody>
        <tr *ngFor="let data of tableData; let i = index">
            <td *ngFor="let cell of data">
              {{ cell }}
            </td>
        </tr>
    </tbody>
</table>
like image 82
BogdanC Avatar answered Mar 09 '26 03:03

BogdanC