Align with the optional chaining spec
See original GitHub issue🚀 feature request
Relevant Package
@angular/compiler
Description
Optional chaining[1] reached stage 4. We’ve been supporting similar syntax in templates for a while now, calling it the “safe navigation operator”[2]. For simplicity and smaller payload, we can consider aligning with the spec in future versions of the framework.
There are a couple of semantical and syntactical differences between optional chaining and safe navigation.
Syntax
Optional chaining has the following syntax:
obj?.prop // optional static property access
obj?.[expr] // optional dynamic property access
func?.(...args) // optional function or method call
Safe navigation supports only direct property access. Optional chaining supports this, as well as, method calls and function calls. Function calls are particularly useful in iterators:
iterator.return?.()
Semantics
With optional chaining, the expression a?.b will be translated to a == null ? undefined : a.b. In Angular, the semantics of the same expression would be null == a ? null : a.b.
If a is null or undefined, the expression typeof a?.b would evaluate to "object" with optional chaining and "undefined" in Angular’s safe navigation operator.
Except the mentioned difference above, method calls are compiled similarly:
a?.b()
a == null ? undefined : a.b()
In both, optional chaining and safe navigation in templates, stacking the operators is translated the same way: (a?.b).c?.d becomes null == a ? null : null == a.b.c ? null : a.b.c.d.
Another difference seems to be the way parentheses are handled. The optional chaining spec defines that null==e.foo?null:e.foo.b.c should be translated to (a == null ? undefined : a.b).c. In Angular the same expression translates to null == a ? null : a.b.c.
PS: looks like the last issue is fixed by https://github.com/angular/angular/pull/34221.
[1] Optional chaining spec https://github.com/tc39/proposal-optional-chaining [2] Safe navigation https://angular.io/guide/template-syntax#safe-navigation-operator
Issue Analytics
- State:
- Created 4 years ago
- Reactions:116
- Comments:28 (5 by maintainers)

Top Related StackOverflow Question
The problem with angular’s syntax is that there’s no way to check that the array isn’t undefined or null. Yes, what you show will check to see if the array has that indexed item, but if I want to know that the property is in fact initialized, I have to do
foo?.bar && foo?.bar[0]?It would be much better to use optional chaining and just use
foo?.bar?.[0]?Just to check, does this cover the case of array-index optional chaining (
arr?.[0]) in templates? I get an error when I try to use that today, though I’m not sure if it’s a problem Angular itself or just the language service.