Simple custom Angular (Angular2) Pipe that extends Number
/We have a lot of code that looks like this in our new Angular (Angular2) module:
<div style="width:210px"> <div> {{ (overviewDetails.TotalTurnoverActualSecured ? (overviewDetails.TotalTurnoverActualSecured / 1000000) : 0) | number:'1.2-2' }} </div> <div>{{ overviewDetails.TotalTurnoverActualSP / 1000000 | number:'1.2-2' }}</div> <div>{{ overviewDetails.TotalTurnoverActualSPF / 1000000 | number:'1.2-2' }}</div> <div style="clear:both"></div> </div>
The main reason is that we just want to display numbers in 1.2 million, not 1200,000.
So obviously, we think about wrapping this in a custom Pipe function.
number is a Pipe name for the DecimalPipe class. So we can extend that and borrow all the work the DecimalPipe does with parsing and formatting.
import { Pipe } from '@angular/core'; import { DecimalPipe } from '@angular/common'; @Pipe({ name: 'million' }) export class MillionPipe extends DecimalPipe { transform(value: number): any { return super.transform(((value || 0)/ 1000000), "1.2-2"); } }
The Angular2 template then simplifies down to:
<div style="width:210px"> <div>{{ overviewDetails.TotalTurnoverActualSecured | million }}</div> <div>{{ overviewDetails.TotalTurnoverActualSP | million }}</div> <div>{{ overviewDetails.TotalTurnoverActualSPF | million }}</div> <div style="clear:both"></div> </div>
It is so nice to work with a Proper Object-Oriented language like TypeScript here. Look at that extends. <3