The API I am working with returns this if there are no items in the array
items: []
If there are items in the array it returns something like
items: [ { name: 'Bla' } ]
In my template I believe I need to use ng-if to either show/hide an element based on whether there is data in there or not.
<p ng-if="post.capabilities.items"><strong>Topics</strong>: <span ng-repeat="topic in post.capabilities.items">{{topic.name}}</p>
However I could be totally off base as this is my first time working in Angular, and there may be a much better way to do what I am trying to do.
We can also explicitly check if the array is empty or not. if (arr. length === 0) { console. log("Array is empty!") }
The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.
An empty array is falsey in PHP, so you don't even need to use empty() as others have suggested. PHP's empty() determines if a variable doesn't exist or has a falsey value (like array() , 0 , null , false , etc). In most cases you just want to check !$ emptyVar .
To check if an array is empty in React, access its length property, e.g. arr. length . If an array's length is equal to 0 , then it is empty. If the array's length is greater than 0 , it isn't empty.
post.capabilities.items
will still be defined because it's an empty array, if you check post.capabilities.items.length
it should work fine because 0
is falsy.
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