Question mark in Angular expressions

This post is 4 years old. (Or older!) Code samples may not work, screenshots may be missing and links could be broken. Although some of the content may be relevant please take it with a pinch of salt.

In some code examples you may have seen that Angular expressions have a question mark after them - this is what Angular refers to as the 'safe navigation operator'. In this article we'll investigate what it does.

In a nutshell the safe navigation operator makes sure that we are not seeing null and undefined values in our application when we want to access properties of an object.

Consider a scenario where we have an object created in our component which gets populated by data coming from an HTTP service:

// sample code
export class CharacterDisplayComponent implements OnInit {
constructor(private http: HttpClient) {}
product;
ngOnInit() {
this.http
.get('http://my.api/product/1')
.subscribe((response: any) => (this.product = response));
}
}

Now, in our template we'd do something similar to this:

<p>My product price is: </p>

The above will yield a null reference error in the browser console: TypeError: Cannot read property 'price' of null in [null].

The issue here is that we are trying to access a property of an object which does not have the response from the API yet.

There are two ways that we can use to overcome this issue - one is to use ngIf and the other is the safe navigation operator.

ngIf

We can make the part of the page appear only if a class member (in our case - product) is not null:

<div *ngIf="product">
<p>My product price is: </p>
</div>

This will work because Angular will not even render the div's content unless product is not null, which means that once product has some value assigned to it, it's safe to access the properties belonging to them.

Safe Navigation Operator

The second way is to apply the question mark syntax on the property that we are working with, therefore our code would look like this in the template:

<p>My product price is: </p>

The above is product?.price is really an equilvaent of the following ternary if statement:

product !== null ? product.price : null

This safe navigation operator is a good way to guard against null and undefined values in property paths when accessing data.