angular - 如何在 Angular 2的小数管道中使用变量

标签 angular angular2-template

我想为带有 Angular 2 中的动态变量的数字格式化创建一个小数管道

十进制管道示例 - number_expression | number[:digitInfo] 其中 digitInfo 是具有以下格式的字符串: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

我希望通过我的代码设置 {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

最佳答案

自己写管道,这是官方文档中的示例:

    import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 |  exponentialStrength:10}}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent: string): number {
    let exp = parseFloat(exponent);
    return Math.pow(value, isNaN(exp) ? 1 : exp);
  }
}

让我们编写 DecimalNumberPipe

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

@Pipe({name: 'decimalNumber'})
export class DecimalNumberPipe implements PipeTransform {
  transform(value: number, decimal: string): number {
    let dec = value - Math.floor(value)
    return dec;// write your formatting code here
  }
}

关于angular - 如何在 Angular 2的小数管道中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43319322/

相关文章:

css - Bootstrap 表的自定义加载消息(替换 "Loading, please wait...")

Angular 4 HttpClient header 丢失

html - 如何在模型框中获取 Google 位置

angular - 如何绑定(bind)到 angular2 中投影内容中的属性?

javascript - Angular 4 应用程序错误 : "core.es5.js:1169 Uncaught Error: No provider for PlatformRef!"

javascript - Protractor 在 promise 后找不到相同的元素

javascript - 双向绑定(bind) : array of numbers within angular application

html - 当表格中的输入失去焦点时如何触发 "focusout"事件?

javascript - 根据服务响应动态显示/隐藏输入框

angular - 从 NgForm 中检索 NgModel