如何在模板语法中获取数组的长度

Tam*_*mpa 13 angular

我试图在模板语法中评估下面的数组:

FAIL 
{{ cols.length }}
Run Code Online (Sandbox Code Playgroud)

我得到以下错误.

platform-browser.umd.js:1900 ORIGINAL EXCEPTION: TypeError: Cannot read property 'length' of undefined
Run Code Online (Sandbox Code Playgroud)

但我会迭代所以我知道该部分有效:

      SUCCESS
     <th *ngFor="let h of cols"> 
        {{h}}
      </th>
Run Code Online (Sandbox Code Playgroud)

Har*_*inh 57

使用

{{ cols?.length }}
Run Code Online (Sandbox Code Playgroud)

要么

<div *ngIf="cols">{{ cols.length }}</div>
Run Code Online (Sandbox Code Playgroud)

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

{{ cols?.length || '0' }}
Run Code Online (Sandbox Code Playgroud)

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