知向前端
Angular 给展示的数字添加一个数字格式千分位管道
2020-5-5 Jon

最终效果
242 => 242
369511 => 369,511
41262132 => 41,262,132
6456122331 => 6,456,122,331




  1. 在共享模块 shared 模块中创建数字管道



ng g p shared/pipe/number-format




  1. 在 shared 模块中导出管道



...
import { NumberFormatPipe } from './pipe/number-format.pipe';
@NgModule({
declarations: [NumberFormatPipe],
...
exports: [
...
NumberFormatPipe
],
...
})



  1. 编写管道代码



// 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;
}
}



  1. 在需要使用该管道的组件对应的模块中导入 shared 模块



import { SharedModule } from '@app/shared';
@NgModule({
...
imports: [
SharedModule,
...
]
})



  1. 在组件中使用管道



  <div class="num">{{ '12332132132' | numberFormat }}</div>



测试数字是否被转换为千分位格式。至此,一个简单的 Angular 数字格式化管道就完成了。



评论:
Jon
2020-05-10 22:06 回复
@吹梦到西洲:换好了
吹梦到西洲
2020-05-10 20:00 回复
@Jon:站长好~麻烦更新一下域名吧~
吹梦到西洲 原域名:https://blog.geog.top 更新为:https://blog.loli.top

谢谢!麻烦了~
Jon
2020-05-08 09:42 回复
@吹梦到西洲:主要是技术,
吹梦到西洲
2020-05-07 18:21 回复
一直博主都是个技术博客
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容