本文介绍了Angular2 * ng如果检查模板中的对象数组长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考 https://angular.io/docs/ts/最新/指南/displaying-data.html 并堆叠来检查angular 2模板中的空对象,仍然会得到语法错误自定义上下文.如果我删除* ngIf条件,那么如果我在其中添加一些值,那么我将在teamMembers中获取值,以便可以访问teamMembers中的值.

我的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[];

任何帮助都会很棒.

解决方案
 <div class="row" *ngIf="teamMembers?.length > 0">
 

这首先检查teamMembers是否具有值,并且teamMembers没有值,它不会尝试访问undefinedlength,因为条件的第一部分已经失败./p>

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

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.

这篇关于Angular2 * ng如果检查模板中的对象数组长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:58