[javascript] ng-if check if array is empty

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.

This question is related to javascript arrays angularjs

The answer is


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.


In my experience, doing this on the HTML template proved difficult so I decided to use an event to call a function on TS and then check the condition. If true make condition equals to true and then use that variable on the ngIf on HTML

    emptyClause(array:any) {


        if (array.length === 0) {
            // array empty or does not exist

            this.emptyMessage=false;

    }else{

            this.emptyMessage=true;
        }
}

HTML

        <div class="row">

        <form>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
            <div class="col-md-10 col-sm-10 col-xs-10">
        <div [hidden]="emptyMessage" class="alert alert-danger">

            No Clauses Have Been Identified For the Search Criteria

        </div>
            </div>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
        </form>


Verify the length property of the array to be greater than 0:

<p ng-if="post.capabilities.items.length > 0">
   <strong>Topics</strong>: 
   <span ng-repeat="topic in post.capabilities.items">
     {{topic.name}}
   </span>
</p>

Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items"> evaluates always to true, even if the array is empty.


To overcome the null / undefined issue, try using the ? operator to check existence:

<p ng-if="post?.capabilities?.items?.length > 0">
  • Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf:

    <p *ngIf="post?.capabilities?.items?.length > 0">
    

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature