How to check type of variable in ngIf in Angular2

Globals like window, typeof, enums, or static methods are not available within a template. Only members of the component class and typescript language constructs are available.

You can add a helper method to your component like

isNumber(val): boolean { return typeof val === 'number'; }

and use it like

<label class='number' *ngIf='isNumber(obj[key])'>

Alternatively, you can compare the constructor name.

{{ foo.constructor.name === 'FooClass' }}

Detailed info about this here.


You can create simple pipe which will receive current item and return item type.

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

@Pipe({
  name: 'typeof'
})
export class TypeofPipe implements PipeTransform {

  transform(value: any): any {
    console.log("Pipe works ", typeof value);
    return typeof value;
  }

}

Now you can use typeof pipe in html like this

*ngIf = (item | typeof) === 'number'

And be careful in using function call in your html as mentioned above. It preferred to use pipe instead of function call. Here is Stackblitz example. In first case function call will triggered on any change detection (example: clicking on buttons).