How to get length of array in template syntax

前端 未结 2 1940
小鲜肉
小鲜肉 2021-02-01 21:24

I am trying to evaluate the below in template syntax which is an array:

FAIL 
{{ cols.length }}

I get the below error.

platfo         


        
相关标签:
2条回答
  • 2021-02-01 21:27

    Use

    {{ cols?.length }}
    

    Or

    <div *ngIf="cols">{{ cols.length }}</div>
    

    If you want to print 0 for empty array, use

    {{ cols?.length || '0' }}
    

    Reason: cols is not initiated when Angular2 load the template. And we want to wait until it's ready to access its members.

    0 讨论(0)
  • 2021-02-01 21:36

    Try defining the cols variable as an object list on .ts archive cols: object[];

    If you want to print 0 for an empty array use the ternary operator:

    {{ cols ? cols.length : '0' }}
    
    0 讨论(0)
提交回复
热议问题