Skip to main content

Question mark in Angular expressions

2 min read

Older Article

This article was published 8 years ago. Some information may be outdated or no longer applicable.

You might’ve spotted a question mark after some Angular expressions in code examples. Angular calls this the ‘safe navigation operator’. Let’s look at what it does.

The safe navigation operator guards against null and undefined values when you’re trying to access properties of an object.

Consider a scenario where an object in your component gets populated by data 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));
  }
}

In the template, you’d do something like this:

<p>My product price is: {{ product.price }}</p>

That throws a null reference error in the browser console: TypeError: Cannot read property 'price' of null in [null].

The problem: you’re trying to access a property on an object that hasn’t received the API response yet.

Two ways to fix this: ngIf or the safe navigation operator.

ngIf

You can make part of the page appear only when the class member (in our case, product) isn’t null:

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

This works because Angular won’t render the div’s content until product has a value. Once it does, accessing its properties is safe.

Safe Navigation Operator

The second approach is the question mark syntax on the property you’re accessing:

<p>My product price is: {{ product?.price }}</p>

The expression product?.price is really equivalent to this ternary statement:

product !== null ? product.price : null

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