Angular2 * ngIf 检查模板中对象数组的长度

引用 https://angular.io/docs/ts/latest/guide/displaying-data.html和堆栈 如何使用 * ngIf 检查角度2模板中的空对象仍然得到语法错误自上下文未定义。如果我移除 * ngIf 条件,那么如果我向其中添加一些值,那么我就可以获得 TeamMember 中的值,这样我就可以访问 Teammember 中的值。

我的 teamMember对象是 [ ] array我试图检查条件数组是空的大小。

尝试:

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

还有

<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({
selector: 'pbi-editor',
})
export class AppComponent implements OnInit {
teamMembers: User[];

任何帮助都可以。

255633 次浏览

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

<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.

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.

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>

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.