0

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>

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.