-1

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>
Developer
  • 1,567
  • 6
  • 18
  • 52

2 Answers2

1

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.

nash11
  • 6,414
  • 2
  • 8
  • 43
1

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

Chellappan வ
  • 15,213
  • 2
  • 16
  • 42
  • Please don't use function call in template,It will cause an unnecessary change detection therefore it will cause performance issue. Be aware of it. – Chellappan வ Sep 06 '19 at 06:56