Ali*_*ine 5 if-statement angular-ng-if angular
我希望当值隐藏标签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>
Run Code Online (Sandbox Code Playgroud)
我确定ngIf可以正常工作,因为我设置了一个条件,如果该值大于0。它可以工作,但仍然不是我的需要
// > 0
<mat-hint *ngIf="this.cost_liter != null" >cost/liter: {{this.cost_liter}}</mat-hint>
Run Code Online (Sandbox Code Playgroud)
您可以使用 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>
Run Code Online (Sandbox Code Playgroud)
或者,您可以在组件中定义一个方法,并在每次需要时调用它。
isNumber(value) {
return Number.isNaN(value);
}
Run Code Online (Sandbox Code Playgroud)
并在模板中使用:
<mat-hint *ngIf="!isNumber(this.cost_liter)" >cost/liter: {{this.cost_liter}}</mat-hint>
Run Code Online (Sandbox Code Playgroud)
由于方法 isNan 在您的模板中不知道,您可以在组件中声明它:
isNaN: Function = Number.isNaN;
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中这样称呼它:
<mat-hint *ngIf="!isNAN(this.cost_liter)" >cost/liter: {{this.cost_liter}}</mat-hint>
Run Code Online (Sandbox Code Playgroud)
问候,
| 归档时间: |
|
| 查看次数: |
1392 次 |
| 最近记录: |