/ Angular

Question mark in Angular expression

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) { }

  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: {{ product.price }}</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.


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: {{ product.price }}</p>

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: {{ product?.price }}</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.

Tamas Piros

Tamas Piros

Tamas is a full stack web developer turned technical trainer who has a decade of experience working with prestigious organisations and has delivered training classes all over the world.

Read More