Gourav Pokharkar
Gourav Pokharkar

Reputation: 1638

Clarity on Safe Navigation Operator in Angular

Angular Docs says:

Sometimes however, null values in the property path may be OK under certain circumstances, especially when the value starts out null but the data arrives eventually.

With the safe navigation operator, ?, Angular stops evaluating the expression when it hits the first null value and renders the view without errors.

I'm finding little ambiguity over here. Does it say that using Safe Navigation Operator will not render (update) data which was null at first but eventually got changed say because of AJAX call updated that object after some time?

Upvotes: 0

Views: 1572

Answers (2)

Charles Robertson
Charles Robertson

Reputation: 1820

Also, be very careful when using the safe navigation operator in an 'if' clause, when you are trying to evaluate whether an object property exists or not.

If you have a boolean, as a property value, and it is false, the program won't execute inside the 'if' clause, like:

const data = {
 showProducts  = false;
};

if( data?.showProducts ){
 ...
}

If you want to see if a property exists or not, use:

if( 'showProducts' in data ){
 ...
}

The safe navigation operator definitely has its uses, but just be careful when using it, with falsey values.

I probably could have lest this answer as a comment. but I am sick and tired of not being able to format my comments.

Upvotes: 0

lealceldeiro
lealceldeiro

Reputation: 14958

Does it says that using Safe Navigation Operator will not render(update) data which was null at first but eventually got changed say because of AJAX call updated that object after some time?

No. It means that the expression is not evaluated after it detects some null value (but won't stop from rendering if it changes in the future to some non-null value).

For example if in component.ts you have

val = null;
// ...
someService.someMethod().susbcribe(val => this.val);

and in the component.html you have

{{val?.someProperty}}

Initially nothing will be rendered because val is null.

Now, once some value arrives inside the susbcribe and this.val gets some non-null value, the value of val.someProperty is rendered in the view.

See a demo using a timeout.

Upvotes: 4

Related Questions