Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use isArray() in Angular 2+ template?

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?

like image 517
Bhushan Gadekar Avatar asked Jun 07 '16 11:06

Bhushan Gadekar


2 Answers

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)"
like image 170
tchelidze Avatar answered Sep 23 '22 09:09

tchelidze


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)"
like image 45
Estus Flask Avatar answered Sep 21 '22 09:09

Estus Flask