Reputation: 820
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>
Upvotes: 26
Views: 12603
Reputation: 19397
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?.
Upvotes: 40
Reputation: 27254
The other answers amount to the same thing, but I find foo && foo[0]
to be the most readable. The right side of the logical-and operator won't be evaluated if the left side is falsy, so you safely get undefined
(or I guess null
, if you don't believe Douglas Crockford.) with minimal extra characters.
For that matter, you asked for a "simpler" solution, but actually *ngIf
is probably correct for the use case you gave. If you use any of the answers here, you'll wind up with an empty h6
tag that you didn't need. If you make the tag itself conditional, you can just put foo[0]
in the handlebars and be confident that it won't be evaluated when foo
is still undefined, plus you never pollute the page with an empty tag.
Upvotes: 0
Reputation: 6494
Of cause it's a matter of taste, but in such cases I tend to use a shorter approach:
<h6>{{(simpleData || [])[0]}}</h6>
Upvotes: 8
Reputation: 29614
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>
Upvotes: 12