如何在角度4中创建自定义管道,并使用一些资源格式化数字(accounting.js)

时间:2017-09-13 02:37:25

标签: angular

这是问题(我的背景是铁轨,我还在学习角4)

我有会计javascript文件(.js)(accounting.js),其功能 accounting.formatNumber()我想在angular中使用。 我做了一些搜索,我发现npmjs package for this js并安装了 npm install accounting-js ,我还找到了accounting.d.ts。现在问题,请考虑以上资源如何创建自定义管道以使用此功能。

这里是我想要实现的结果,在我的html视图中使用函数(例如我有proposal-list.component.html),我希望{{123456.78 | formatNumber}}将打印到屏幕123,456.78

我确实发了一个question previously并且有人给了我custom pipe的线索,我确实测试过直接使用js但仍然没有运气(见下面的代码)

提案-list.component.ts

import { Component, OnInit } from '@angular/core';
import { formatNumber } from 'accounting-js/lib/formatNumber.js';
@Component({
  selector: 'app-proposal-list',
  templateUrl: './proposal-list.component.html',
  styleUrls: ['./proposal-list.component.css']
})
export class ProposalListComponent implements OnInit {
  totalMoney: number = 0;
  constructor() { }
  ngOnInit() {
    this.totalMoney = formatNumber(123456.78)
  }
}

提案-list.component.html

<p>test = {{ totalMoney }}</p>

它显示没有值的标签测试,

3 个答案:

答案 0 :(得分:1)

我根据文化面临类似的数字转换问题所以我用 ECMAScript Intl API编写了一个自定义管道

代码基本上是这样的:

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

  @Pipe({
  name: 'numberLocale'
})
export class NumberLocalePipe implements PipeTransform {

  transform(value: any, selectedCulture: any): any {

    if (!value) {
      return;
    }
    var userLang = navigator.language;
    if (selectedCulture) {
      return new Intl.NumberFormat(selectedCulture).format(value);
    } else {
      return new Intl.NumberFormat(userLang).format(value);
    }

  }

}

在这里,我使用ECMAScript的Intl.NumberFormat,您可以使用account.js无变化。

您可以在我为您创建的working Plunkr 中看到完整的代码。

希望这会对你有所帮助。

答案 1 :(得分:0)

首先使用angular-cli生成新管道,命令为:ng g pipe format-number然后:

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

@Pipe({name: 'formatNumber'})
export class FormatNumberPipe implements PipeTransform {
  transform(value: number): number {
    // there You should write your formula for transforming numbers into string like: 123456.78 into 123,456.78
  }
}

答案 2 :(得分:0)

有一个默认的货币管道为您执行此操作。

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

如果您不想使用它,请使用javascript

<p>test = {{ totalMoney.toLocaleString() }}</p>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

相关问题