I've been seeing this creep up in a few places now but have not found any answers on it.
I'm curious what the '!' bang does in the angular syntax.
From the Angular documentation:
The non-null assertion operator ( ! )
As of Typescript 2.0, you can enforce strict null checking with the
--strictNullChecks
flag. TypeScript then ensures that no variable is unintentionallynull
orundefined
.In this mode, typed variables disallow
null
andundefined
by default. The type checker throws an error if you leave a variable unassigned or try to assignnull
orundefined
to a variable whose type disallowsnull
andundefined
.The type checker also throws an error if it can't determine whether a variable will be
null
orundefined
at runtime. You may know that can't happen but the type checker doesn't know. You tell the type checker that it can't happen by applying the post-fix non-null assertion operator (!).The Angular non-null assertion operator (!) serves the same purpose in an Angular template.
For example, after you use
*ngIf
to check thathero
is defined, you can assert thathero
properties are also defined.<!-- No hero, no text --> <div *ngIf="hero"> The hero's name is {{hero!.name}} </div>
When the Angular compiler turns your template into TypeScript code, it prevents TypeScript from reporting that
hero.name
might benull
orundefined
.Unlike the safe navigation operator, the non-null assertion operator does not guard against
null
orundefined
. Rather it tells the TypeScript type checker to suspend strict null checks for a specific property expression.You'll need this template operator when you turn on strict null checks. It's optional otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With