Angular Equivalent of Null Coalescing Operator in HTML Template

Viewed 1233

What is the equivalent of null coalescing operator ?? in Angular HTML Template? Is it OR Operator?

Goal: If Product Name is null, display ProductType

{{ (item?.ProductName || item.ProductType) }}

using ?? operator in HTML template, gives me an error.

2 Answers

I think I have a solution for you please check code below=>
HTML:

<p>
 {{ item?.ProductName==undefined?item.ProductType:item.ProductName }}
</p>

TS:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  item:MyClass;
  constructor(){
    this.item=new MyClass();
    //this.item.ProductName="P-Name";
    this.item.ProductType="P-Type";
    console.log(this.item.ProductName);
  }
}
export class MyClass{
  ProductName :string;
  ProductType :string;
}

Note: If you enable this.item.ProductName="P-Name"; this line it will show "P-Name" otherwise it will show "P-Type". StackBlitz Link.

This "??" operator exists only in Angular version 12. Using previous versions I think you will have to use the basic ternary operator.

<input [defaultValue]="this.variable != null ? this.variable : ''">
</input>
Related