# Question mark in Angular expressions

Source: https://tpiros.dev/blog/question-mark-in-angular-expression

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:

```typescript
// sample code

  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:

```html
<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:

```html
<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:

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

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

```html
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.
