简体   繁体   中英

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?

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.

这对我*ngIf= "(grade|json) == 'null' "

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM