Skip to main content

What is the ! operator (non-null assertion) used for in a template?

In Angular, the ! operator (non-null assertion) in a template is used to tell the TypeScript compiler that a value is definitely not null and not undefined, even if the variable's type allows those values.

Main points

  1. Syntax in a template:
html
<p>{{ user!.name }}</p>
  • Tells Angular: "I am sure that user exists at render time."
  • The compiler will not raise the error "Object is possibly 'null' or 'undefined'".
  1. Use with bindings:
html
<input [value]="user!.email">
  • Allows using an object's properties without additional null checks.
  1. Important to understand:
  • This is only an assertion for the compiler.
  • If the value actually turns out to be null or undefined at runtime, the error will still occur.

In other words, ! is a way to bypass TypeScript's strict type checking when the developer is sure the value is present.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.