17

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?

4 Answers 4

32

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)"
1
  • Are we allowed to use private variables in templates ? Template do not exist within component class but outside the component class. May 26, 2021 at 8:25
11

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)"
6

In addition to what @tchelidze said:

Angular 2 provides a wrapper called isArray in facade/lang exported and defined like this:

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

You can import it into your component like this:

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

Then you could expose it publicly in your component:

this.isArray = isArray

And use in your template like so:

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

2

Angular way: https://angular.io/guide/pipes

is-array.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'isArray' })
export class IsArrayPipe implements PipeTransform {
  transform(value: unknown): boolean {
      return Array.isArray(value);
  }
}

my.component.html

<div *ngIf="selectedCol.model.data | isArray">...</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.