Search code examples
javascriptionic-frameworktyposcript

How to display multidimensional array with *ngFor?


I newbe in js,ts,ionic

I got this array called 'stores' in my home.ts:

0: {name: "wwwe", floor: 1}
1: {name: "weeqe", floor: -3}
2: {name: "weewqe", floor: -2}
3: {name: "qweqweqwe", floor: -2}

And I need too show it through *ngFor. I have this in home.html:

<ion-card *ngFor="let store of stores">
<ion-card-header >
{{store.name}}
</ion-card-header>
</ion-card>

But this is show empty page!

Help pls

Also I tryed this:

<ion-card *ngFor="let store of stores; let i=index">
<ion-card-header >
{{store[i].name}}
</ion-card-header>
</ion-card>

Dont work.

I read that I must to change the object to an array, but I do not understand how to do this in my case. I need all the array values in one place.

home.ts:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {


constructor(public navCtrl: NavController, public http: Http) {
    var stores: Store[] = []
    var json;
    this.http.get('http/link/to/json').map(res => res.json()).subscribe(data => {
            json = data.data;
            for (var i of json.stores){
                stores.push({ 'name': i.name, 'floor': i.floor[0]  });
            }

        });

    console.log(stores);

  }


}

This is show console.log(stores) :

https://i.sstatic.net/TGsys.png


Solution

  • You have to declare stores variable outside the constructor

    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import { Http } from '@angular/http';
    import 'rxjs/add/operator/map';
    
    @Component({
    selector: 'page-home',
    templateUrl: 'home.html'
    })
    export class HomePage {
    
    // This way so you can reference it in the ngFor
    stores: Store[] = [] 
    
    constructor(public navCtrl: NavController, public http: Http) {
        var json;
        this.http.get('http/link/to/json').map(res => res.json()).subscribe(data => {
                json = data.data;
                for (var i of json.stores){
                    this.stores.push({ 'name': i.name, 'floor': i.floor[0]  });
                }
    
            });
    
        console.log(this.stores);
    
      }
    
    
    }