Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like a Safe Navigation Operator that can be used on Arrays?

I have used Safe Navigation Operator for Objects to load on Asynchronous calls and it is pretty amazing. I thought I could reproduce the same for Arrays but it displays a template parse error in my Angular code. I know *ngIf is an alternative solution, but is there a more simpler(by code) way just like the Safe Navigation Operator?

<div class="mock">
   <h5>{{data?.title}}</h5>  //This works
   <h6>{{data?.body}}</h6>  //This works
   <h6>{{simpleData?[0]}}</h6>  // This is what I tried to implement    
</div>
like image 605
Sriram Jayaraman Avatar asked Jun 20 '17 07:06

Sriram Jayaraman


People also ask

What is safe navigation operator in angular?

The Angular safe navigation operator, ? , guards against null and undefined values in property paths. Here, it protects against a view render failure if item is null .

What does safe navigation operator do?

Use the safe navigation operator ( ?. ) to replace explicit, sequential checks for null references. This operator short-circuits expressions that attempt to operate on a null value and returns null instead of throwing a NullPointerException.

What is safe navigation operator TypeScript?

Safe navigation operator or optional chaining is now available in JavaScript and TypeScript >= v3. 7🎉. It provides easy access to deeply nested values, so checking for nullish ( undefined or null ) values is simplified.

What is safe navigation operator Ruby?

Safe navigation operator¶ ↑ &. , called “safe navigation operator”, allows to skip method call when receiver is nil . It returns nil and doesn't evaluate method's arguments if the call is skipped.


3 Answers

Is there something like a Safe Navigation Operator that can be used on Arrays?

Yes, what you are looking for is known as the Optional Chaining operator (JavaScript / TypeScript).

The syntax shown in the MDN JavaScript documentation is:

obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

So, to achieve what you want, you need to change your example from:

<h6>{{simpleData?[0]}}</h6>

To:

<h6>{{simpleData?.[0]}}</h6>
                 ^

Also see How to use optional chaining with array in Typescript?.

like image 179
DavidRR Avatar answered Sep 18 '22 20:09

DavidRR


is there a more simpler(by code) way just like the Safe Navigation Operator?

There is ternary operator.

condition ? expr1 : expr2

<h6>{{simpleData?simpleData[0]:''}}</h6>   
like image 12
Suraj Rao Avatar answered Sep 20 '22 20:09

Suraj Rao


Of cause it's a matter of taste, but in such cases I tend to use a shorter approach:

<h6>{{(simpleData || [])[0]}}</h6>
like image 7
Alex Vayda Avatar answered Sep 19 '22 20:09

Alex Vayda