How to set condition of a NaN value to show/hide a view using ngIf | angular 6

Viewed 9012

I want to hide a label when the value is NAN using *ngIf* but it's not working.

The marked label is the default value of a variable, once the input is filled the value will be a number I want to show the label only when the value is not NAN

What tried

     // undefined
    <mat-hint *ngIf="this.cost_liter !== 'undefined'" >cost/liter: {{this.cost_liter}}</mat-hint>
   // 'undefined'
    <mat-hint *ngIf="this.cost_liter !== 'undefined'" >cost/liter: {{this.cost_liter}}</mat-hint>
    //!=
    <mat-hint *ngIf="this.cost_liter != undefined" >cost/liter: {{this.cost_liter}}</mat-hint>
    //!== NAN
    <mat-hint *ngIf="this.cost_liter !== NAN" >cost/liter: {{this.cost_liter}}</mat-hint>
     //!= NAN
  <mat-hint *ngIf="this.cost_liter != NAN" >cost/liter: {{this.cost_liter}}</mat-hint>
     //!== null
   <mat-hint *ngIf="this.cost_liter !== null" >cost/liter: {{this.cost_liter}}</mat-hint>
    // != null
   <mat-hint *ngIf="this.cost_liter != null" >cost/liter: {{this.cost_liter}}</mat-hint>

i am sure that ngIf is working, since i set a condition if the value greater than 0. and it works, but still not my need

    // > 0
   <mat-hint *ngIf="this.cost_liter != null" >cost/liter: {{this.cost_liter}}</mat-hint>
2 Answers

You can use JavaScript method isNAN(this.cost_liter) to check or you can use Number.isNaN().

Use if (Number.isNaN(this.cost_liter))

Both methods return true or false, and returns false if the value is null.

This is how you do:

<mat-hint *ngIf="!Number.isNaN(this.cost_liter)" >cost/liter: {{this.cost_liter}}</mat-hint>

Or you can define a method in the component and call each time you need it.

isNumber(value) {
  return Number.isNaN(value);
}

And use in the template:

<mat-hint *ngIf="!isNumber(this.cost_liter)" >cost/liter: {{this.cost_liter}}</mat-hint>

Since the method isNan is not know in you template , you can declare it in the component :

isNaN: Function = Number.isNaN;

then in your template call it like this :

<mat-hint *ngIf="!isNAN(this.cost_liter)" >cost/liter: {{this.cost_liter}}</mat-hint>

Regards,

Related