从angular2中的数字管道中删除逗号

问题描述 投票:6回答:3

我是Angular 2的初学者。我正在尝试使用angular显示一些数据。这是我的代码部分:

  <span>Value :</span> <span>{{myvalue| number : '1.2-2'}}</span>

以上部分将显示值,例如:“124,500.00”。没问题,但我需要删除逗号并显示数据仅为124500.00。这也不是货币类型。

我试过这样的事情,但是没有用

   <span>Value :</span> <span>{{myvalue| number: '.2-3''}}</span>

我该怎么做?我可以使用任何自定义管道吗?

提前致谢

angular angular-pipe
3个回答
15
投票

实际上,看起来DecimalPipe没有直接参数来更改或删除小数点。编写自己的管道以删除小数点可能是最好的。

您可以编写自己的管道来完全替换当前使用的DecimalPipe(用于所有内容的单个管道),也可以编写一个管道,在使用DecimalPipe(链接管道)后删除逗号。最后一个选项可能看起来像这样(我从this回答代码,所以问候Adrien)。

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

@Pipe({
  name: 'noComma'
})
export class NoCommaPipe implements PipeTransform {

  transform(val: number): string {
    if (val !== undefined && val !== null) {
      // here we just remove the commas from value
      return val.toString().replace(/,/g, "");
    } else {
      return "";
    }
  }
}

你可以像这样链接管道。

 <span>Value :</span> <span>{{myvalue| number : '1.2-2' | noComma}}</span>

只需记住在模块中声明管道。


2
投票

更改了REPLACE参数,以便删除所有逗号(10,000,000 = 10000000),否则我最终得到(10,000,000 = 10000,000)。根据Benedikt,其他一切都运作良好。

@Pipe({
    name: 'noComma'
})
export class NoCommaPipe implements PipeTransform {

 transform(val: number): string {
  if (val !== undefined && val !== null) {
    // here we just remove the commas from value
    return val.toString().replace(/,/g, "");
  } else {
    return "";
  }
 }
}

0
投票

角度数使用decimalPipe,此解决方案适用于角度2和更多

https://angular.io/api/common/DecimalPipe

由于它使用的是区域设置,因此您必须更改区域设置以更改管道显示它的方式

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

// the second parameter 'fr' is optional
registerLocaleData(localeFr, 'fr');

供参考:https://angular.io/guide/i18n#i18n-pipes

© www.soinside.com 2019 - 2024. All rights reserved.