新建管道:
ng g pipe pipes/money
或
ng g p pipes/money
pipes/money.pipe.ts,同时在父级module.ts加入
import { MoneyPipe } from './pipes/money.pipe';
@NgModule({ declarations: [ ... ]})里面加入MoneyPipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'money' })
export class MoneyPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
if (value) return (args[0] || '') + parseFloat(parseFloat(value).toFixed(2)).toLocaleString() + (args[1] || '');
else return 0;
return null;
}
}
app.component.html
<h1>{{123456789.123456789 | money}}</h1>
<h1>{{123456789.123456789 | money:'¥':'元'}}</h1>
<h1>{{123456789.123456789 | money:'人民币':'万元'}}</h1>
呈现内容
额外的,pipe是可以多个联合使用,譬如酱紫↓
<h1>{{123456789.123456789 | money | otherPipe | otherMorePipe}}</h1>