【问题标题】:How to set condition of a NaN value to show/hide a view using ngIf | angular 6如何使用 ngIf 设置 NaN 值的条件以显示/隐藏视图 |角度 6
【发布时间】:2019-04-13 09:28:20
【问题描述】:

我想在值为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>

【问题讨论】:

  • NaN != NaN 是 JavaScript 的一个有趣的小怪癖,所以你的比较总是会返回 true。

标签: angular if-statement angular-ng-if


【解决方案1】:

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

isNaN: Function = Number.isNaN;

然后在你的模板中这样称呼它:

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

问候,

【讨论】:

  • 请问可以在ts组件中指定isNaN函数的添加位置吗?我试图在类声明中添加它,但不起作用,在ngOnInit() 中但仍然不起作用,问候
  • 您应该将其添加为组件的属性:export class yourComponent { isNaN: Function = Number.isNaN;构造函数(){} }
  • 这正是我尝试过的,但我收到了这个错误FuelContainerComponent.html:28 ERROR TypeError: _co.isNAN is not a function
  • 你能说明你是如何在 html 模板中使用它的吗? (如您所见,错误在您的 html 中)
  • ts:isNaN: Function = Number.isNaN; constructor(private fuelContServ: FuelContainerService,private modalService: NgbModal,public snackBar: MatSnackBar) {}html:&lt;input matInput formControlName="totalPrice" placeholder="Total Price" type="number" [(ngModel)]="this.totalPrice" name="nameInput" (ngModelChange)="this.cost_liter=this.totalPrice/this.totalLiters"&gt; &lt;mat-hint *ngIf="!isNAN(this.cost_liter)" &gt;cost/liter: {{this.cost_liter}}&lt;/mat-hint&gt;
【解决方案2】:

您可以使用JavaScript方法isNAN(this.cost_liter)进行检查,也可以使用Number.isNaN()

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

这两种方法都返回true或false,如果值为null则返回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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 2017-08-17
    相关资源
    最近更新 更多