DEV Community

Tomas
Tomas

Posted on

Protect your templates without tedious *ngIfs

Problem:
Properties we use in our templates are sometimes undefined or null, this can cause our templates not to render. We can protect our code by wrapping the potential problem area with an *ngIf, but that quickly becomes cumbersome for longer property paths.

Solution:
By utilizing Angulars safe navigator operator ?., also called the Elvis operator, we can reduce unnecessary checks in our templates, by making sure we only access properties that could be null or undefined via the safe navigator operator.

Before / Untutored:

Component

pastery = {
    name: 'Cinnamon bun',
    ingredients: {
      eggs: null,
      milk: null
    }
}

Template

<h2>Ingredients</h2>

<div *ngIf="pastery.ingredients.eggs">
  {{ pastery.ingredients.eggs.qty.amount }} {{ pastery.ingredients.eggs.qty.unit && pastery.ingredients.eggs.qty.unit.name }} {{ pastery.ingredients.eggs.name }}
</div>

<div *ngIf="pastery.ingredients.milk">
  {{ pastery.ingredients.milk.qty.amount }} {{ pastery.ingredients.milk.qty.unit && pastery.ingredients.milk.qty.unit.name }} {{ pastery.ingredients.milk.name }}
</div>

After:

Component

pastery = {
    name: 'Cinnamon bun',
    ingredients: {
      eggs: null,
      milk: null
    }
}

Template

<h2>Ingredients</h2>

<div>
 {{ pastery.ingredients.eggs?.qty.amount }} {{ pastery.ingredients.eggs?.qty.unit?.name }} {{ pastery.ingredients.eggs?.name }}
</div>

<div>
  {{ pastery.ingredients.milk?.qty.amount }} {{ pastery.ingredients.milk?.qty.unit?.name }} {{ pastery.ingredients.milk?.name }}
</div>

Try it yourself:
https://stackblitz.com/edit/thllbrg-angular-fika-3

Official docs:
https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

Top comments (0)