[javascript] How to check empty object in angular 2 template using *ngIf

I want to check if my object is empty dont render my element, and this is my code:

<div class="comeBack_up" *ngIf="previous_info != {}">
   <a 
      [routerLink]="['Inside_group_page',{'name':previous_info.path | dotTodash }]"
      >
        {{previous_info.title}}
   </a>
</div>

but my code is wrong, what is the best way to do this?

This question is related to javascript typescript angular

The answer is


This should do what you want:

<div class="comeBack_up" *ngIf="(previous_info | json) != ({} | json)">

or shorter

<div class="comeBack_up" *ngIf="(previous_info | json) != '{}'">

Each {} creates a new instance and ==== comparison of different objects instances always results in false. When they are convert to strings === results to true

Plunker example


Just for readability created library ngx-if-empty-or-has-items it will check if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).

arrayOrObjWithData = ['1'] || {id: 1}

<h1 *ngxIfNotEmpty="arrayOrObjWithData">
  You will see it
</h1>

 or 
 // store the result of async pipe in variable
 <h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
  {{obj.id}}
</h1>

 or

noData = [] || {}
<h1 *ngxIfHasItems="noData">
   You will NOT see it
</h1>

A bit of a lengthier way (if interested in it):

In your typescript code do this:

this.objectLength = Object.keys(this.previous_info).length != 0;

And in the template:

ngIf="objectLength != 0"

This worked for me:

Check the length property and use ? to avoid undefined errors.

So your example would be:

<div class="comeBack_up" *ngIf="previous_info?.length">

UPDATE

The length property only exists on arrays. Since the question was about objects, use Object.getOwnPropertyNames(obj) to get an array of properties from the object. The example becomes:

<div class="comeBack_up" *ngIf="previous_info  && Object.getOwnPropertyNames(previous_info).length > 0">

The previous_info && is added to check if the object exists. If it evaluates to true the next statement checks if the object has at least on proporty. It does not check whether the property has a value.


You could also use something like that:

<div class="comeBack_up" *ngIf="isEmptyObject(previous_info)"  >

with the isEmptyObject method defined in your component:

isEmptyObject(obj) {
  return (obj && (Object.keys(obj).length === 0));
}

Above answers are okay. But I have found a really nice option to use following in the view:

{{previous_info?.title}}

probably duplicated question Angular2 - error if don't check if {{object.field}} exists


From the above answeres, following did not work or less preferable:

  • (previous_info | json) != '{}' works only for {} empty case, not for null or undefined case
  • Object.getOwnPropertyNames(previous_info).length also did not work, as Object is not accessible in the template
  • I would not like to create a dedicated variable this.objectLength = Object.keys(this.previous_info).length !=0;
  • I would not like to create a dedicated function

    isEmptyObject(obj) {
       return (obj && (Object.keys(obj).length === 0));
    }
    

Solution: keyvalue pipe along with ?. (safe navigation operator); and it seems simple.

It works well when previous_info = null or previous_info = undefined or previous_info = {} and treats as falsy value.

<div  *ngIf="(previous_info | keyvalue)?.length">

keyvalue - Transforms Object or Map into an array of key value pairs.

?. - The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined

DEMO: demo with angular 9, though it works for previous versions as well


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 typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7