Mohammad Fareed
Mohammad Fareed

Reputation: 1972

Angular check json has children or empty

Want to check child and child variables or empty

{{ CustomJsonSchema?.properties | json }} // if empty returns {}
{{ CustomJsonSchema?.properties | json }} // if not empty returns { "street_1": { "type": "string" }, "zip_code": { "type": "string" }, "first_name": { "type": "string" } }

HTML :

<div>Has Elements</div>
<div>Empty</div>

Upvotes: 0

Views: 937

Answers (2)

nash11
nash11

Reputation: 8660

Edit

While this approach will work, it will unnecessarily trigger the isEmpty function on every change detection even if there are no changes to the object. For a more efficient approach, follow @Chellapan's method.


You can create a function in your component to check if your object is empty and use it in your template.

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

Depending on the ECMAScript version or whether you are using a third-party library like lodash or underscore, you can check out this answer for the different ways to check if an object is empty.

Then in your template

<div *ngIf="CustomJsonSchema?.properties && isEmpty(CustomJsonSchema.properties)">
    Empty
</div>
<div *ngIf="CustomJsonSchema?.properties && !isEmpty(CustomJsonSchema.properties)">
    Has elements
</div>

The first condition is to make sure CustomJsonSchema.properties exists before checking if it is empty.

Upvotes: 2

Chellappan வ
Chellappan வ

Reputation: 27333

Create custom pipe. Then use ngIf else directive to show different elements in html

isEmpty.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'isEmpty'
})
export class IsEmptyPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    let keys = value && Object.keys(value);
    return Array.isArray(keys);
  }

}

component.html

<div *ngIf="CustomJsonSchema | isEmpty else noData">
  has Value
</div>
<ng-template #noData>
   Empty
</ng-template>

Example

Upvotes: 1

Related Questions