When I use ?
, the binding works well. If I remove it, it doesn't show anything in the view.
<span class="subhead">{{project?.category}}</span>
Can you please tell me the difference? Is it a good practice to use it this way?
The non-null assertion operator ( ! ) The Angular non-null assertion operator causes the TypeScript type checker to suspend strict null and undefined checks for a specific property expression. For example, you can assert that item properties are also defined.
Syntaxlink The following JavaScript and template expression syntax is not allowed: new. Increment and decrement operators, ++ and -- Operator assignment, such as += and -=
In some code snippets, you may have seen that Angular expressions have a question mark after them. Angular refers to it as 'Safe Navigation Operator'. It makes sure that we are not seeing null and undefined values in our application when we want to access properties of an object.
Two-way data bindingThe template can change the value of the data-bound class property and the class can change the value of the property in the template. The template and the class are bound to each other, any change in either of them results in data updates in both of them.
When Angular renders the view before project
got a value assigned, it causes an exception. ?.
stops evaluating when project
is null
or undefined
, which usually happens when data is fetched async, for example from the server which can take quite some time.
The next time change detection recognizes a change, the bindings will be re-evaluated. When project
then has a value it will bind project.category
.
?
is the safe navigation operator. It checks whether the variable is null
or undefined
so that our template won't try to select a property of something falsy.
More info: https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths
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