Angular2 *ngIf check object array length in template

后端 未结 5 642
北恋
北恋 2020-12-12 23:43

Refered to https://angular.io/docs/ts/latest/guide/displaying-data.html and stack How to check empty object in angular 2 template using *ngIf still getting syntax error self

相关标签:
5条回答
  • 2020-12-12 23:45

    Maybe slight overkill but created library ngx-if-empty-or-has-items it checks if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).

    arrayOrObjWithData = ['1'] || {id: 1}
    
    <h1 *ngxIfNotEmpty="arrayOrObjWithData">
      You will see it
    </h1>
    
     or 
     // store the result of async pipe in variable
     <h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
      {{obj.id}}
    </h1>
    
     or
    
    noData = [] || {}
    <h1 *ngxIfHasItems="noData">
       You will NOT see it
    </h1>
    
    0 讨论(0)
  • 2020-12-12 23:47
    <div class="row" *ngIf="teamMembers?.length > 0">
    

    This checks first if teamMembers has a value and if teamMembers doesn't have a value, it doesn't try to access length of undefined because the first part of the condition already fails.

    0 讨论(0)
  • 2020-12-12 23:51

    You could use *ngIf="teamMembers != 0" to check whether data is present

    0 讨论(0)
  • 2020-12-13 00:07

    This article helped me alot figuring out why it wasn't working for me either. It give me a lesson to think of the webpage loading and how angular 2 interacts as a timeline and not just the point in time i'm thinking of. I didn't see anyone else mention this point, so I will...

    The reason the *ngIf is needed because it will try to check the length of that variable before the rest of the OnInit stuff happens, and throw the "length undefined" error. So thats why you add the ? because it won't exist yet, but it will soon.

    0 讨论(0)
  • 2020-12-13 00:08

    You can use

    <div class="col-sm-12" *ngIf="event.attendees?.length">
    

    Without event.attendees?.length > 0 or even event.attendees?length != 0

    Because ?.length already return boolean value.

    If in array will be something it will display it else not.

    0 讨论(0)
提交回复
热议问题