如何在模板语法中获取数组的长度 [英] How to get length of array in template syntax

查看:74
本文介绍了如何在模板语法中获取数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数组形式的模板语法评估以下内容:

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

FAIL 
{{ cols.length }}

我收到以下错误.

platform-browser.umd.js:1900 ORIGINAL EXCEPTION: TypeError: Cannot read property 'length' of undefined

但是我进行了迭代,所以我知道该部分有效:

But I do iterate so I know that portion works:

      SUCCESS
     <th *ngFor="let h of cols"> 
        {{h}}
      </th>

推荐答案

使用

{{ cols?.length }}

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

如果要为空数组打印0,请使用

If you want to print 0 for empty array, use

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

原因:Angular2加载模板时,不会启动 cols .我们要等到它准备好访问其成员.

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

这篇关于如何在模板语法中获取数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆