首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在角4中使用一些资源创建自定义管道以格式化编号(accounting.js)

如何在角4中使用一些资源创建自定义管道以格式化编号(accounting.js)
EN

Stack Overflow用户
提问于 2017-09-13 02:37:24
回答 3查看 916关注 0票数 2

这就是问题所在(我的背景是rails,我还在学习角4)

我有会计javascript文件(.js) (accounting.js),它有函数.js,我想在angular中使用它。我做了一些搜索,我找到了这个js的npmjs包,并安装了npm安装会计-js,我还找到了accounting.d.ts。现在的问题是,考虑上面的资源如何创建自定义管道来使用这个函数。

在这里,我想要实现的结果,使用我的html视图中的函数(例如,我有提案-list.Component.html)和我想要的{{ 123456.78 x formatNumber }将打印到屏幕123,456.78。

我确实发布了一个以前的问题,有人给了我一个关于定制管的提示,我做了直接使用js的测试,但仍然没有结果(参见下面的代码)

proposal-list.component.ts

代码语言:javascript
复制
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)
  }
}

proposal-list.component.html

代码语言:javascript
复制
<p>test = {{ totalMoney }}</p>

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-09-13 06:14:55

我面临着一个类似的按照文化进行数字转换的问题,所以我用ECMAScript Intl API编写了一个自定义管道。

代码基本上是这样的:

代码语言:javascript
复制
     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);
    }

  }

}

在这里,我使用的是Intl.NumberFormat of ECMAScript,您可以使用您的account.js,没有太大的更改。

在我为您创建的这个工作普朗克尔中可以看到整个代码。

希望这能帮到你。

票数 1
EN

Stack Overflow用户

发布于 2017-09-13 03:55:16

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

代码语言:javascript
复制
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
  }
}
票数 0
EN

Stack Overflow用户

发布于 2017-09-13 04:32:35

有一个默认的货币管道为您提供此功能。

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

如果您不想使用它,那么使用javascript

代码语言:javascript
复制
<p>test = {{ totalMoney.toLocaleString() }}</p>

对象/数字/toLocaleString

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46187966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档