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.
This is because the request which returns
restaurantis asynchronous. Therefore,restaurantwill be undefined when the component is first rendered, until the observable from therestaurantdetailmethod is returned.The elvis operator, also known as the safe navigation operator,
Therefore, it is required on your HTML template:
An alternative to doing so would be to use the ngIf structural directive which checks if
restaurantis null or undefined.