如何在Angular 4中创建自定义管道,并使用一些资源以格式编号(Accounting.JS)



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

我有具有函数 Accounting.formatNumber()的会计JavaScript文件(.js)(Accounting.js),我想在Angular中使用。我进行了一些搜索,我找到了此JS的NPMJS软件包,并使用 npm install councting-js 安装,我还找到了Accounting.D.TS。现在,问题要考虑如何创建自定义管道使用此功能的资源。

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

我以前确实发布了一个问题,有人给我一个自定义管道的线索,我确实测试了直接使用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>

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

我面临着类似的数字转换问题

代码基本上是这样的:

     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没有太大的更改。

您在我为您创建的此工作的Plunkr中可以看到的整个代码。

希望这对您有所帮助。

首先使用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
  }
}

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

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/tolecalestring

相关内容

最新更新