Nullish Coalescing in Angular Templates
Hello everyone,
Let's talk about Nullish Coalescing (??). While reviewing the Angular 12 release notes, I noticed this operator and how it enables cleaner TypeScript code. Angular 12 now supports Nullish Coalescing (??) directly within view templates.
First, let's clarify what Nullish Coalescing (??) actually means before examining its template support in Angular 12.
Understanding Nullish Coalescing (??)
Nullish refers specifically to null or undefined.
Coalescing means bringing elements together into one unit.
As a logical operator, the nullish coalescing operator (??) evaluates the right-hand operand only when the left-hand operand is null or undefined. In all other cases, the left-hand operand is returned.
const a = null ?? 'hello world';
console.log(a);
// output: "hello world"
const b = 0 ?? 2;
console.log(b);
// output: 0
Usage syntax -
(Left side expression) ?? ( Right side expression)
Note: The nullish coalescing operator sidesteps a common pitfall because it triggers the second operand only for null or undefined, not for other falsy values such as '' or 0.
It's also worth mentioning that mixing && or || with ?? without parentheses is prohibited. You must add parentheses to ensure the precedence is unambiguous.
Invalid usage 🚫
null || undefined ?? "Hello World"; // raises a SyntaxError
true || undefined ?? "Hello World"; // raises a SyntaxError
Valid usage ✅
(null || undefined) ?? "Hello World ";
// Output "Hello World"
Now that Nullish Coalescing (??) is clear, let's see how Angular 12 integrates it.
Consider a current template scenario where imageUrl may be assigned by a component or a child component. If imageURL remains unset, the fallback is getRandomImages() as the default value.
{{imageURL !== null && imageURL !== undefined ? imageURL : defaultImageURL }}
This can be simplified using Nullish Coalescing (??)
{{ this.imageURL ?? this.defaultImageURL }}
Thank you for reading. I hope this concept is now clear. For any questions, feel free to reach out on Twitter at @aviboy2006 or open an issue on the GitHub repository. If you found it helpful, please consider starring the repo.
References :

