ngFor from object?

I’m using Ionic 2 / Angular, but I realized that the ngFor function can’t read objects. Also, I need it to be shown only if the cart is not empty.

Object:

{
    "48131": {
        "code":"D40905",
        "name":"ДАМСКА ПЛЕТЕНА БЛУЗА КЪС РЪКАВ ЩАМПА REASON",
        "price":"18.99",
        "size":"STANDART",
        "qty":"1"
    },
    "49410": {
        "code":"D41821",
        "name":"ДАМСКА БЛУЗА ТРИКО",
        "price":"44.99",
        "size":"M",
        "qty":"4"
    }
}

HTML:

<ion-row *ngFor="let p of cart">
    <ion-col col-3>
        <div><img src="http://example.com/products/small/{{p.code}}-1.jpg" /></div>
    </ion-col>
    <ion-col col-9>
        <ion-row>
            <ion-col col-12>
                <div>{{p.name}}</div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div>{{p.qty}} бр ({{p.size}} размер) x <b>{{p.price}} лв</b></div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div (click)="deleteCart({{p.id}})">Изтрий <ion-icon name='trash' item-start color="danger"></ion-icon></div>
            </ion-col>
        </ion-row>
    </ion-col>
</ion-row>

Can someone help me with this? I’ve tried so many things…

Maybe try using ngFor with ngIf?

    <ion-item *ngFor="let p of cart">
        <ng-container *ngIf="something">
        </ng-container>
    </ion-item>
1 Like

Hi,
you should transform your object to an array.

For example with a function like this:

var objectToArray = function(obj) {
  var arr =[];
  for(let o in obj) {
    if (obj.hasOwnProperty(o)) {
      arr.push(obj[o]);
    }
  }
  return arr;
};

Then you use this for the ngFor loop, if the array is empty nothing will show up as expected.

Hope this helps.

1 Like

Oh, thanks a lot! It worked! Just one more thing - how do I echo <p>Your cart is empty</p> if the array is empty?

Edit: Never mind, I just used <p *ngIf="cart?.length > 0">Your cart is empty.</p>.

1 Like