Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property of undefined angular2 ngif

I am now able to get the object in the view however I cannot run an if statement. Per previous answer this is how I am bringing in the object.

public getPosts$(category, limit) {
  return this.cartService.getPosts(category, limit).map(response => {
    return response && response.data && response.data.children;
  };
}

ngOnInit() {
  this.getPosts$(this.category, this.limit).subscribe(cart => {
    this.cart = cart;
  }
}

I am trying to run but get cannot get property vegetable.

<h2 *ngIf="cart">{{cart.vegetable}}</h2>
<h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>

The error is

Cannot read property 'vegtable' of undefined

like image 477
Matt Avatar asked Feb 01 '17 17:02

Matt


1 Answers

The cart object is null until the service getPosts$ returns (callback). Therefore, the code *ngIf="cart.vegetable ... is equal to *ngIf="null.vegetable ... until that happens. That is what is happening.

What you could do is put a DOM element with *ngIf="cart" containing the other *ngIf. For example:

<div *ngIf="cart">
    <h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
</div>

*Edit: As it is said in the next answer, a good alternative (and good practice) is the following:

<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>

like image 121
Codeicus Avatar answered Sep 23 '22 15:09

Codeicus