Why do I need Safe Navigation operator (Elvis) if I am initializing an object in Angular

281 views Asked by At

Angular 8, Django 3. I am displaying an object Restaurant in a view RestaurantView. The RestaurantView gets the Restaurant on the ngOnInit method:

    restaurant: Restaurant
    id: string 

    getrestaurantdetail(id):void {
      this.restaurantservice.restaurantdetail(id).subscribe(restaurant => this.restaurant = restaurant)
    }


  ngOnInit() {
    this.id = this.route.snapshot.paramMap.get('id')
    this.getrestaurantdetail(this.id)
  }

}

and then is diplayed in the html file <h1>{{restaurant.name}}</h1>. If I dont put the Elvis operator in the html file as <h1>{{restaurant?.name}}</h1> the view displays correctly but I get a console error property "name" not defined. I dont understand if the RestaurantView is returning a Restaurant object on initialization why I would ever get this null error.

1

There are 1 answers

0
wentjun On

This is because the request which returns restaurant is asynchronous. Therefore, restaurant will be undefined when the component is first rendered, until the observable from the restaurantdetail method is returned.

The elvis operator, also known as the safe navigation operator,

guards against null and undefined values in property paths. Here, it protects against a view render failure if item is null.

Therefore, it is required on your HTML template:

<h1>{{restaurant?.name}}</h1>

An alternative to doing so would be to use the ngIf structural directive which checks if restaurant is null or undefined.

<h1 *ngIf="restaurant">{{restaurant.name}}</h1>