user10127693
user10127693

Reputation:

Variable in component.html is undefined in angular 6

This is a function in my appservice.ts to fetch products from local storage

 getproducts(){
    const storedCart = this.storage.get(this.key);
    if (storedCart != null) {
        this.mycart = storedCart;
        return this.mycart;
    }
else{
    return null;
}

}

And this is my cart component.ts where I am using appservice to call that method

export class CartComponent implements OnInit {
  carts:Cart[]=[];
  constructor(private appservice:AppService) { }
  getcartproducts(){
    this.carts=this.appservice.getproducts();//calling appservice
  }

  ngOnInit() {
  this.getcartproducts();

  }}

Now in my cartcomponent.html

 <tr class="rem1" valign="middle" *ngFor="let cart of carts;let i = index">
 <div class="entry value"><span>{{cart[i].quantity}}</span></div>
</tr>

This above code gives me error as

cannot read property 'quantity' of undefined

I dont know where I am doing wrong ,any help will be really appreciated !!

Upvotes: 1

Views: 2568

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

cart is an Object, you don't have an index on object, change it as

 <div class="entry value"><span>{{cart?.quantity}}</span></div>

Upvotes: 2

Related Questions