Reputation: 1435
I am working on the Ionic Ecommerce App and I am showing the products with the size in the cart and some products have size and some don't have the size but the problem is that the products that doesn't have the size is showing the size label in the cart.
This is my cart.html:
<p *ngIf="ifSize">Size: {{itm?.psize}}</p>
In this view, I am showing the size for the products.
This is my cart.ts:
import { CheckoutPage } from './../checkout/checkout';
import { Component, ChangeDetectorRef } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
import { CartProvider } from "../../providers/cart/cart";
@IonicPage()
@Component({
selector: 'page-cart',
templateUrl: 'cart.html',
})
export class CartPage {
cartItems: any[] = [];
totalAmount: number = 0;
isCartItemLoaded: boolean = false;
isEmptyCart: boolean = true;
ifSize: boolean = true;
productCount: number = 1;
constructor(public navCtrl: NavController, public navParams: NavParams, private cartService: CartProvider, public loadingCtrl: LoadingController, private alertCtrl: AlertController, private cdr: ChangeDetectorRef) {
}
ionViewDidLoad() {
this.loadCartItems();
}
loadCartItems() {
let loader = this.loadingCtrl.create({
content: "Wait.."
});
loader.present();
this.cartService
.getCartItems()
.then(val => {
this.cartItems = val;
console.log(val);
if(val.psize === undefined)
{
this.ifSize = false;
}
if (this.cartItems.length > 0) {
this.cartItems.forEach((v, indx) => {
this.totalAmount += parseInt(v.totalPrice);
});
this.cdr.detectChanges();
this.isEmptyCart = false;
}
this.isCartItemLoaded = true;
loader.dismiss();
})
.catch(err => {});
}
}
In this ts file, By default it will show the size for all the products and the products that doesn't have the size for that the size label will hide. But the problem is that console.log(val); is coming like the array of products. So that's why I am not able to find the size of the products in the array and also not able to apply the correct condition for the size in the array of the products. Any help is much appreciated. Result of:
console.log(val);
Upvotes: 1
Views: 242
Reputation: 1353
val.psize
doesnt return anything in your case because you need val[0].psize, val[1].psize
so on... To solve this problem, remove this one:
if(val.psize === undefined)
{
this.ifSize = false;
}
Add here v.psize
and check inside the foreach like this:
if (this.cartItems.length > 0) {
this.cartItems.forEach((v, indx) => {
//---Add here
if(v.psize===undefined){
this.ifSize = false;
}else{
this.ifSize = true;
}
//---
this.totalAmount += parseInt(v.totalPrice);
});
this.cdr.detectChanges();
this.isEmptyCart = false;
}
then your code should work as expected
Edit: Maybe your looking this one, I m kinda confused:
<p *ngIf="itm?.psize!== undefined">Size: {{itm?.psize}}</p>
Upvotes: 2