我想为带有 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/