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.
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
--strictNullChecksflag. TypeScript then ensures that no variable is unintentionallynullorundefined.In this mode, typed variables disallow
nullandundefinedby default. The type checker throws an error if you leave a variable unassigned or try to assignnullorundefinedto a variable whose type disallowsnullandundefined.The type checker also throws an error if it can't determine whether a variable will be
nullorundefinedat 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
*ngIfto check thatherois defined, you can assert thatheroproperties 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.namemight benullorundefined.Unlike the safe navigation operator, the non-null assertion operator does not guard against
nullorundefined. 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.
Its called the "Non-null assertion operator" and has nothing todo with Angular perse, it is from typescript.
let s = e!.name; // Assert that e is non-null and access name