2016-06-07 72 views
11

我有這個變量名爲records,如何在打字稿中使用isArray()?

現在我想檢查它的數組或不在angular2/typescript?

在AngularJS我用來做下列的程序:

ng-if="selectedCol.data && !isArray(selectedCol.data)" 

但是當我嘗試做以下它不工作;

*ngIf="selectedCol.model.data && !Array.isArray(selectedCol.model.data)" 

它給我下面的錯誤:

TypeError: Cannot read property 'isArray' of undefined any inputs?

回答

12

角2模板內Component的背景,意義執行,你可以在裏面Component

最簡單的方式定義只訪問屬性/方法是在您的方法中定義isArray方法Component

isArray(obj : any) { 
    return Array.isArray(obj) 
} 

在模板

*ngIf="isArray(selectedCol.model.data)" 

爲了避免樣板代碼,與isArray方法定義服務,註冊爲單件,注入Component和經由服務屬性

備選地使用isArray方法,定義_array屬性在您的Component中,並指定Array鍵入它

private _array = Array; 

在模板

*ngIf="_array.isArray(selectedCol.model.data)" 
5

除了什麼@tchelidze說:

角2提供了名爲isArrayfacade/lang出口和確定這樣的包裝:

export function isArray(obj: any): boolean { 
    return Array.isArray(obj); 
} 

您可以導入它進入你的組件像這樣:

import {isArray} from '@angular/facade/lang'; 

然後,你可以在您的組件公開揭露它:

this.isArray = isArray

而在你的模板中使用像這樣:

*ng-if="selectedCol.data && !isArray(selectedCol.data)"

1

雖然不是最有效的解決方案(見其他答案),[].constructor.isArray適用於任何表達上下文,並且不需要使用語言級幫助器污染組件類:

*ngIf="selectedCol.model.data && [].constructor.isArray(selectedCol.model.data)"