Unable to read undefined angular2 ngif property

Now I can get the object in the view, but I can not run the if statement. In the previous answer, this is how I enter 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 cannot get the vegetable property.

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

Error

Unable to read property 'vegtable' undefined

+4
source share
2 answers

The object cartis null until the service getPosts$returns (callback). Therefore, the code *ngIf="cart.vegetable ...is equal *ngIf="null.vegetable ...until this happens. This is what happens.

What you can do is put a DOM c element *ngIf="cart"containing another *ngIf. For instance:

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

* Edit: , ( ) :

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

+8

null undefined :

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

Source: https://habr.com/ru/post/1668550/


All Articles