Lea
Lea

Reputation: 1285

Angular2 How to ngIf empty object or array

I am getting json object from the server and they are deep nested.

Anyway, I want to show 'The user hasn't filled in yet' when the json object is empty (or array)

I tried almost everything but they didn't work. What am I doing wrong?

<div class="common-container" *ngFor="let detail of deepTeaInfo | getValues">
  <div id="exp-box" *ngFor="let grade of detail['introduceInfo']['grade'] | getValues">
    <p class="fontstyle3">Grade: <span class="fontstyle2">{{grade.category | type_transform}}</span></p>
    <p class="fontstyle3">Period: <span class="fontstyle2"> {{grade.when | type_transform}}</span></p>
    <p class="fontstyle3">Description: <span class="fontstyle2"> {{grade.description}}</span> </p>

    <p class="fontstyle2" *ngIf="grade?.length > 0">
      The user hasn't filled in yet
    </p>
  </div>
  <br>
</div>

The things I've tried

 *ngIf="grade?.length > 0"

*ngIf = "(grade|json) == '{}'"

*ngIf = "grade.length >0"

*ngIf = "(grade|json).length >0"

*ngIf "(grade|json) == ({}|json)"

they didn't work.

If I {{grade.json}} in the html, I see something like

 {when: 2011, description: temp, category: school},
 {when: 2011, description: temp, category: school}

If I {{grade}} in the html, I see

 [object Object]
 [object Object]

(I know that the array is empty seeing from the json string that I got from the server :))

What am I doing wrong?

Upvotes: 0

Views: 8371

Answers (3)

Sumit
Sumit

Reputation: 881

Your question/code doesn't seem to be sufficient to tell whether its array or object.

Case 1: Array

    <div *ngIf="array?.length">

Duplicate https://stackoverflow.com/a/55177735/2488600

Case 2: Object

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

Duplicate https://stackoverflow.com/a/56532650/2488600

Upvotes: 2

Pragati Kerur
Pragati Kerur

Reputation: 145

This worked for me *ngIf= "(grade|json) == 'null' "

Upvotes: 0

Deepender Sharma
Deepender Sharma

Reputation: 490

for each object you should store it in a model and in template you can easily check whether that particular model has data or not. This is the ideal way to store the nested json objects into the models.

Upvotes: 0

Related Questions