新建管道:
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;}}
ponent.html
<h1>{{123456789.123456789 | money}}</h1><h1>{{123456789.123456789 | money:'¥':'元'}}</h1><h1>{{123456789.123456789 | money:'人民币':'万元'}}</h1>
呈现内容
额外的,pipe是可以多个联合使用,譬如酱紫↓
<h1>{{123456789.123456789 | money | otherPipe | otherMorePipe}}</h1>
扩展阅读【不明觉厉】Angular的 pure pipe (纯管道) 和 impure pipe (非纯管道) 是啥意思?_你挚爱的强哥()-CSDN博客纯管道和非纯管道是相对于管道所传的参数(如上例的 filterKey)而言的。如果管道是纯管道,只监听基本类型的参数的变化或者引用类型引用的变化(a primitive input value (String,Number,Boolean,Symbol) or a changed object reference (Date,Array,Function,Object));然而, 对于非纯管道,不管是基本类型参数的改变还是引用类型内部数据变化(而非引用变化)都可以触发管道。@Pip.../qq_37860634/article/details/120408160
Angualr设置自定义管道Pipe(类似Vue的过滤器filters)货币格式化(实现内置管道CurrencyPipe的功能)