如何使用 ngIf | 将 NaN 值的条件设置为 show/hide 视图angular 6

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

我想在值为 NAN 时使用 *ngIf* 隐藏标签,但它不起作用。

标记的标签是一个变量的默认值,一旦输入填充该值将是一个数字 我只想在值不是 NAN

时显示标签

尝试了什么

     // 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>

我确定 ngIf 有效,因为我设置了一个条件,如果值大于 0。它有效,但仍然不是我的需要

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

您可以使用JavaScript方法isNAN(this.cost_liter)检查或者您可以使用Number.isNaN().

使用if (Number.isNaN(this.cost_liter))

两种方法 return true 或 false,如果值为 null returns false。

你是这样的:

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

或者你可以在组件中定义一个方法,每次需要的时候调用。

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

并在模板中使用:

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

由于您的模板中不知道 isNan 方法,您可以在组件中声明它:

isNaN: Function = Number.isNaN;

然后在您的模板中这样调用它:

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

此致,