简体   繁体   中英

Angular2 *ngIf check object array length in template

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 context undefined. If I remove *ngIf condition then I am getting values in teamMembers if I push some value into it so I can access values in teamMembers.

my teamMember object is [ ] array i am trying to check condition array is empty by size.

Tries :

<div class="row" *ngIf="(teamMembers | json) != '{}'">

and

<div class="row" *ngIf="teamMembers.length > 0"> //Check length great than
                                                 throwing syntax error
            <div class="col-md-12">
                <h4>Team Members</h4>
                <ul class="avatar" *ngFor="let member of teamMembers">
                    <li><a href=""><gravatar-image [size]="80" [email]="member.email"></gravatar-image></a></li>
                </ul>
            </div>
        </div>

Component :

@Component({
selector: 'pbi-editor',
})
export class AppComponent implements OnInit {
teamMembers: User[];

Any help would be great.

<div class="row" *ngIf="teamMembers?.length > 0">

这首先检查teamMembers是否具有值,以及teamMembers没有值,因为条件的第一部分已经失败,所以它不会尝试访问undefined length

您可以使用*ngIf="teamMembers != 0"来检查是否存在数据

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.

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>

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.

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