Mahmoud Mabrouk
Mahmoud Mabrouk

Reputation: 733

Angular2 : using *ngFor for multidimensional array using index

I got this array called cats from page component: which console.log(this.cats); shows me this enter image description here

and i want to bind it in (not so simple) html template which is:

<ion-grid *ngFor="let group of cats">
    <ion-row>
        <ion-col col-2></ion-col>

        <ion-col col-4 >
            <div class="home-hexa" style="background-image: url(assets/img/hexa.png);">
                <i class="icomoon-New-icon-c"></i>
                <p>{{group[0].name}}</p>

            </div>
        </ion-col>
        <ion-col col-4>
            <div class="home-hexa" style="background-image: url(assets/img/hexa.png);">
                <i class="icomoon-Tourism-icon"></i>
                <p>{{group[1].name}}</p>

            </div>
        </ion-col>
        <ion-col col-2></ion-col>
    </ion-row>
    <ion-row>
        <ion-col col-4>
            <div class="home-hexa" style="background-image: url(assets/img/hexa.png);">
                <i class="icomoon-money-icon"></i>
                <p>{{group[2].name}}</p>

            </div>
        </ion-col>
        <ion-col col-4>
            <div class="home-hexa" style="background-image: url(assets/img/hexa.png);">
                <i class="icomoon-Culture-icon"></i>
                <p>{{group[3].name}}</p>

            </div>
        </ion-col>
        <ion-col col-4>
            <div class="home-hexa" style="background-image: url(assets/img/hexa.png);">
                <i class="icomoon-Sport-icon"></i>
                <p>{{group[4].name}}</p>

            </div>
        </ion-col>
    </ion-row>
</ion-grid>

for the first {{group[0].name}} it works well but in the others it gives me error :

Cannot read property 'name' of undefined

i do this because i want to loop on every 5 values to bind them manually in ion-grid . how to solve this? sorry for bad english.

Upvotes: 1

Views: 3650

Answers (1)

Salander
Salander

Reputation: 184

If this is your array:

cats=[[{ id:'1', image:'1', name:'g1' }, { id:'1', image:'1', name:'g1' }, { id:'1', image:'1', name:'g1' }, { id:'1', image:'1', name:'g1' }],[ { id:'1', image:'1', name:'f1' },{ id:'1', image:'1', name:'f1' },{ id:'1', image:'1', name:'f1' }] ];

Then use a nested for loop like this:

<div *ngFor="let group of cats">
  <div *ngFor="let obj of group">{{obj.name}}</div>
</div>

You can use this sort of a *ngFor loop as per your need to fetch values from a nested array.

Upvotes: 2

Related Questions