RT:开发过程中偶尔会遇到类似统计的功能,需要把后端返回的数据展示为带单位的字符串。
管道文件transform-data.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'transformData',
pure: true
})
export class TransformDataPipe implements PipeTransform {
transform(value: number, unit: string): string {
const numArr = [];
let i = 0;
if (!value) {
return `0<span class=unit>${unit || '条'}</span>`;
}
const originValue = value;
value = Math.abs(value);
while (value > 0) {
let u = '';
switch (i) {
case 0:
u = unit || '条';
break;
case 1:
u = '万';
break;
case 2:
u = '亿';
break;
}
numArr.unshift((value % 10000) + `<span class=unit>${u}</span>`);
value = Math.floor(value / 10000);
i++;
}
const symbol = originValue < 0 ? '-' : '';
return symbol + numArr.join('');
}
}
使用方法:
首先在module.ts 文件中引入
import { TransformDataPipe } from './transform-data.pipe';
@NgModule({
declarations: [
TransformDataPipe
],
exports: [
TransformDataPipe
]
})
export class SharedModule {}
第二步在html 页面中使用
<div class="count" [innerHtml]="item.value | transformData: item.unit" [title]="item.value"></div>
item 对象
item = {
name: 'XX数量',
value: 65460,
unit: '条'
}
样式 scss
.count {
color: $type-900;
font-size: 20px;
line-height: 28px;
font-weight: 600;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
::ng-deep .unit {
font-size: 12px;
line-height: 20px;
margin: 0 2px;
font-weight: normal;
}
}