How to check type of variable in ngIf in Angular2

后端 未结 5 2062
鱼传尺愫
鱼传尺愫 2020-12-14 05:23

I\'m learning Angular2. I have a component with a variable which is an object. I\'m iterating over the fields of the object, and acording to the type of data of that positio

5条回答
  •  暖寄归人
    2020-12-14 06:08

    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 typeofpipe 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 on clicking on buttons).

提交回复
热议问题