最终效果
242 => 242
369511 => 369,511
41262132 => 41,262,132
6456122331 => 6,456,122,331
- 在共享模块 shared 模块中创建数字管道
ng g p shared/pipe/number-format
- 在 shared 模块中导出管道
...
import { NumberFormatPipe } from './pipe/number-format.pipe';
@NgModule({
declarations: [NumberFormatPipe],
...
exports: [
...
NumberFormatPipe
],
...
})
- 编写管道代码
// number-format.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'numberFormat'
})
export class NumberFormatPipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
return this.toThousands(value);
}
toThousands(num) {
var num = (num || 0).toString(), result = '';
while (num.length > 3) {
result = ',' + num.slice(-3) + result;
num = num.slice(0, num.length - 3);
}
if (num) { result = num + result; }
return result;
}
}
- 在需要使用该管道的组件对应的模块中导入 shared 模块
import { SharedModule } from '@app/shared';
@NgModule({
...
imports: [
SharedModule,
...
]
})
- 在组件中使用管道
<div class="num">{{ '12332132132' | numberFormat }}</div>
测试数字是否被转换为千分位格式。至此,一个简单的 Angular 数字格式化管道就完成了。
2020-05-07 18:21