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.
This checks first if
teamMembers
has a value and ifteamMembers
doesn't have a value, it doesn't try to accesslength
ofundefined
because the first part of the condition already fails.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).
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.
You could use
*ngIf="teamMembers != 0"
to check whether data is present