Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use "?" operator in template binding?

Tags:

angular

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?

like image 663
Sohail Mushtaq Awan Avatar asked Feb 21 '17 10:02

Sohail Mushtaq Awan


People also ask

What is the use of operator in Angular?

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.

Which operator is not supported by template expression in Angular?

Syntaxlink The following JavaScript and template expression syntax is not allowed: new. Increment and decrement operators, ++ and -- Operator assignment, such as += and -=

What is '?' In Angular?

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.

What is Template binding in Angular?

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.


Video Answer


2 Answers

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.

like image 70
Günter Zöchbauer Avatar answered Oct 02 '22 01:10

Günter Zöchbauer


? 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

like image 35
eko Avatar answered Oct 01 '22 23:10

eko