Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 how to iterate through multi-dimensional arrays?

Tags:

arrays

angular

EDIT#2

Unfortunately, I haven't had any success incorporating either one of these suggestions. It's late, so I'm heading off to bed, but I'll try to update tomorrow.

Thanks to Pradeep Jain for the help. I'll also try out the Pipe that evil mind suggested.

I've learned how to use the *ngFor command, but it looks like it only works with simple arrays. Here's the code I'm trying to iterate through.

import {Lesson} from './lesson';

export var LESSONS: Lesson[] = [
{
    "idL": 1,
    "subject": 'Chapter One',
    "points": [
                'picture story', 'spelling test', 'words'
            ]
},
{
    "idL": 2,
    "subject": 'Words',
    "points": [
            'words', 'bacon', 'proliferation'
    ]
}
]

So I am trying to access that second array called "points". I don't think it's improperly formatted, but I haven't been able to figure out how to access it.

I did read about angularJs's foreach command, but Angular2's documentation does not show such a command is available.

Any advice?

like image 393
Nathan Avatar asked May 07 '16 14:05

Nathan


2 Answers

Update (2.0.0)

<table>
    <ng-container *ngFor="let lesson of LESSONS; let i = index">
      <ng-container *ngFor="let point of lesson.points; let j = index">
        <tr>{{point}}</tr>
      </ng-container>
    </ng-container>

<ng-container> is a helper element that is not stamped to the DOM. It allows to use the same syntax as inline *ngIf and *ngFor

Original

Try this one:

<table>
<template ngFor #lesson [ngForOf]="LESSONS" #i="index">
  <template ngFor #point [ngForOf]="lesson.points" #j="index">
  <tr>{{point}}</tr>
  </template>
</template>

Working example Working Plunker.

like image 164
Pardeep Jain Avatar answered Oct 04 '22 20:10

Pardeep Jain


This worked for me in Angular 4, using Pardeep Jain's answer as a basis. Almost the same as StepUps answer, but with ng-containers:

 constructor() {

        this.data = {  
            displayArray:[
                ["Top Row 1st col", "Top Row 2nd col", "Top Row 3rd col"],
                ["Middle Row 1st col", "Middle Row 2nd col", "Middle Row 3rd col"],
                ["Bottom Row 1st col", "Bottom Row 2nd col", "Bottom Row 3rd col"]
            ]
        }

    };

in the template:

<table >
    <ng-container *ngFor="let row of data.displayArray; let i = index">
        <tr>
            <ng-container *ngFor="let col of row; let j = index">
                <td>{{col}}</td>
            </ng-container>
        </tr> 
    </ng-container>
</table>

I didn't need the indexes, but I left them in in case they are needed by others.

like image 29
davaus Avatar answered Oct 04 '22 22:10

davaus