【问题标题】:Ionic-Angular binding not removing DOM element, null number format causes binding to failIonic-Angular 绑定不删除 DOM 元素,空数字格式导致绑定失败
【发布时间】:2017-04-04 21:09:21
【问题描述】:

我绑定了一个变量:

<span *ngIf="myVoltage && myVoltage>=0" > - {{myVoltage | number: '.0-0'}}</span>

根据documentation

ngIf
根据 {expression} 删除或重新创建 DOM 树的一部分。

'myVoltage' 为空,因为它是从服务器检索的,因此如果执行{{myVoltage | number: '.0-0'}},它会抛出某种空异常。这就是为什么我将它放在 span 中:

<span *ngIf="myVoltage && myVoltage>=0" >...</span>

但是它STILL在跨度内的对象上执行绑定和格式化,即使它不应该因为跨度不可见!

例外:null 不是对象(正在评估 'new Intl.NumberFormat(e,u)')

如果我删除| number: '.0-0',那么它会正常显示。然而,按原样,null 异常实际上会导致绑定中断,然后即使值不再为 null,它也永远不会显示。

我的设置信息:

Cordova CLI:6.2.0
离子框架版本:2.0.0-rc.1
Ionic CLI 版本:2.1.8
离子应用程序库版本:2.1.4
Ionic App 脚本版本:0.0.30
ios 部署版本:1.9.0
ios-sim 版本:5.0.11
操作系统:macOS Sierra
节点版本:v6.7.0
Xcode 版本:Xcode 8.1 Build 8B62 版

"dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/compiler-cli": "0.6.2",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/platform-server": "2.0.0",
    "@ionic/storage": "1.0.3",
    "ionic-angular": "2.0.0-rc.1",
    "ionic-native": "2.0.3",
    "ionicons": "3.0.0",
    "moment": "2.14.1",
    "ng2-translate": "3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "0.6.21"
  },
  "devDependencies": {
    "@ionic/app-scripts": "0.0.30",
    "i18next-conv": "3.0.3",
    "typescript": "2.0.6"
  },

我也试过了:

*ngIf="!!busVoltage && busVoltage>=0"
[ngIf]="busVoltage && busVoltage>=0"

编辑 1

所以根据Angular 2 documentation这是正确的做事方式:

<!-- because of the ngIf guard
nullHero.firstName never has a chance to fail -->
<div *ngIf="nullHero">Hello, {{nullHero.firstName}}</div>

编辑 2

所以根据source code

/**
* 警告:此管道使用国际化 API。
* 因此它只在 Chrome 和 Opera 浏览器中可靠。对于其他浏览器,请使用
* polyfill,例如:[https://github.com/andyearnshaw/Intl.js/].

并且根据this answer我需要添加“intl”库,但是我使用了NPM,我不知道在哪里放置以下内容:

import 'intl';
import 'intl/locale-data/jsonp/en';

【问题讨论】:

    标签: angular ionic2


    【解决方案1】:

    我们遇到了类似的问题,我们通过以下解决方法解决了这个问题:我们实现了一个使用 JavaScript's native formatting 的自定义管道:

    if(value === null) {
        return "";
    }
    Intl.NumberFormat().format(value);
    

    这样做的好处是我们从视图中消除了格式化的负担,而且我认为在您的情况下它将消除管道链接。

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2018-12-03
    相关资源
    最近更新 更多