【问题标题】:Display number value with comma instead of dot in <p-column> in Angular在 Angular 的 <p-column> 中用逗号而不是点显示数值
【发布时间】:2018-08-16 21:25:20
【问题描述】:

在我的模板中,我想用逗号而不是点来显示(数字类型的)值作为小数点分隔符。我有:

<p-column field="power" header="Power [MW]" [editable]="true">
  <ng-template let-col let-data="rowData" pTemplate="editor">
    <div>
      <input type="text" [(ngModel)]="data[col.field]" numbersOnly digits="35" decimals="3">
    </div>
  </ng-template>
  <ng-template let-col let-data="rowData" pTemplate="body">
    <div>
      <span>{{ data[col.field] }}</span>
    </div>
  </ng-template>
</p-column>

但这会在编辑器和显示模式中显示带点的数字,例如“10.3”。我需要的是用逗号显示值,比如“10,3”。我该怎么做?

【问题讨论】:

  • 我建议使用自定义管道来根据您的需要重新格式化您的值,看看这里:angular.io/guide/pipes
  • 谢谢。管道在显示模式下工作正常,但如何将它也附加到编辑模式?
  • 非常感谢 tomichel,这对我有帮助!

标签: angular typescript numbers primeng


【解决方案1】:

我不得不通过一个应用程序来解决这个问题,该应用程序从 SAP 接收所有数据,其数字格式为 . 而不是 ,。这是我为解决这个问题而制作的管道,它比adding a locale id 的开销更大,并且使用native angular decimal pipe

Here is a working stackblitz example of the pipe

/**
 * @Pipe
 * @description pipe to format numeric values to argentina readable currency values
 * @input number
 * @output formatted numeric value
 */

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ 
    name: 'numberFormat'
 })
export class NumberFormatPipe implements PipeTransform {
    transform(value: any): number {
        return this.localeString(value);
    }

    missingOneDecimalCheck(nStr) {
        nStr += '';
        const x = nStr.split(',')[1];
        if (x && x.length === 1) return true;   
        return false;
    }

    missingAllDecimalsCheck(nStr) {
        nStr += '';
        const x = nStr.split(',')[1];
        if (!x) return true;    
        return false;
    }

    localeString(nStr) {
        if (nStr === '') return ''; 
        let x, x1, x2, rgx, y1, y2;
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? ',' + x[1] : '';
        rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }

        /** If value was inputed by user, it could have many decimals(up to 7)
            so we need to reformat previous x1 results */
        if (x1.indexOf(',') !== -1) {
            y1 = x1.slice(x1.lastIndexOf(',')).replace(/\./g, '');

            y2 = x1.split(',');
            x = y2[0] +  y1;
        } else {
            x = x1 + x2;
            if (this.missingOneDecimalCheck(x)) return x += '0';
            if (this.missingAllDecimalsCheck(x)) return x += ',00';
        }

        return x;
    }
}

并像这样在您的模板中使用它:

{{ data[col.field] | numberFormat }}

或者在你的组件中

constructor(private format: NumberFormatPipe) {}
...
let result = this.format.transform(some_number);

不要忘记导入并添加到模块声明中:

declarations: [NumberFormatPipe]

请注意,此管道还包含一些检查小数的代码,因为对于我而言,我得到了带小数和不带小数的值,在某些情况下最多有 7 个小数,因此您可以按原样使用它或根据需要对其进行编辑...但我的猜测是,这至少会为您指明正确的方向。

【讨论】:

  • 哦 SAP,我怎么讨厌它
【解决方案2】:

您可以随时将输入字段类型更改为数字

  <input type="number" [(ngModel)]="data[col.field]" numbersOnly digits="35" decimals="3">

它会自动强制它只接受数字。

如果你不需要上下箭头,你可以使用这段 CSS 来隐藏箭头

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    margin: 0;

}

然后您可以强制 Angular 使用特定的语言环境设置。

app.module.ts(适用于瑞典语言环境)

import localeSv from '@angular/common/locales/sv';
import localeSvExtra from '@angular/common/locales/extra/sv';
registerLocaleData(localeSv, 'sv-SE', localeSvExtra)

现在所有数字都神奇地用','表示,如果你将它绑定到你的模型,它将可以毫无问题地绑定到数字类型的字段

【讨论】:

    【解决方案3】:

    您可以简单地通过编写一个角度过滤器来做到这一点,就像我在小提琴中提到的那样,它将用逗号代替点。

    注意:目前我使用静态值进行演示。您可以将其替换为原始模型值。

    var app = angular.module('myapp',['angular.filter'])
    app.controller('myController',['$scope',function($scope){
    $scope.my_modal = 0;
    }])
    app.filter('replaceWithComma', function () {
    return function (text) {
    if(text != undefined) {
    var str = text.toString().replace(".", ",");
    return str;
    }
    };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.11/angular-filter.min.js"></script>
    <div ng-app="myapp" ng-controller="myController">
    <p-column field="power" header="Power [MW]" [editable]="true">
      <ng-template let-col let-data="rowData" pTemplate="editor">
        <div>
          <input type="text" ng-model="my_modal" numbersOnly digits="35" decimals="3">
        </div>
      </ng-template>
      <ng-template let-col let-data="rowData" pTemplate="body">
        <div>
          <span>{{ my_modal | replaceWithComma }}</span>
          <br>Also check with static value:<br>
          <span>{{ 10.30 | replaceWithComma }}</span>
        </div>
      </ng-template>
    </p-column>
    </div>

    【讨论】:

    • 这是 Angular 2 及以上,而不是 Angular js。
    猜你喜欢
    • 2021-06-28
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2015-10-15
    • 2013-01-24
    相关资源
    最近更新 更多