I have this variable named records
,
Now I want to check if its an array or not in angular2/typescript?
In AngularJS I used to do Following:
ng-if="selectedCol.data && !isArray(selectedCol.data)"
But When I am trying to do the Following its not working;
*ngIf="selectedCol.model.data && !Array.isArray(selectedCol.model.data)"
Its giving me below error:
TypeError: Cannot read property 'isArray' of undefined any inputs?
Angular 2 template is executed inside Component
's context, meaning, you can only access properties/methods defined inside Component
Simplest way is to define isArray
method in your Component
isArray(obj : any ) {
return Array.isArray(obj)
}
In template
*ngIf="isArray(selectedCol.model.data)"
To avoid boilerplate code, define Service with isArray
method, register as Singleton, inject into Component
and use isArray
method via Service property
Alternatively, define _array
property in your Component
and assign Array
type to it
private _array = Array;
In template
*ngIf="_array.isArray(selectedCol.model.data)"
While not being the most efficient solution (see the other answer), [].constructor.isArray
is suitable for any expression context and doesn't require to contaminate component classes with language-level helpers:
*ngIf="selectedCol.model.data && [].constructor.isArray(selectedCol.model.data)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With