Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the ! mean in the angular syntax? [duplicate]

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.

enter image description here

like image 260
Christopher Marshall Avatar asked Mar 03 '23 22:03

Christopher Marshall


1 Answers

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 unintentionally null or undefined.

In this mode, typed variables disallow null and undefined by default. The type checker throws an error if you leave a variable unassigned or try to assign null or undefined to a variable whose type disallows null and undefined.

The type checker also throws an error if it can't determine whether a variable will be null or undefined 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 that hero is defined, you can assert that hero 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 be null or undefined.

Unlike the safe navigation operator, the non-null assertion operator does not guard against null or undefined. 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.

like image 94
ConnorsFan Avatar answered Mar 06 '23 22:03

ConnorsFan