Set Default If Null or Undefined | Angular


With Angular 12 version you can use Nullish coalescing operator ?? in templates to set default values if value is null or undefined.

Here is your app.component.ts:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
  constructor(){}

  my_value = null;

  ngOnInit(){}
}

Here is how you can use Nullish coalescing operator ?? in template file app.component.html.

<div>
  {{my_value ?? "my value is null"}}
</div>

So, if my_value is null or undefined it will show the message my value is null. Else it will show the value of variable my_value.