Create a Reusable, Custom Angular 2 Pipe

TSMT

Angular 2 provides a wide variety of pipes – these were called filters in Angular 1.x – for custom display of data.  Of course, if you have been in this business long enough, eventually an application requirement comes along that does not fit the capability provided in the framework.  So, it never hurts to see another example of how to implement your own custom pipe.

This particular example, like all of its predecessors, uses the Typescript Math Toolkit.  An alpha version of the TSMT$NumberFormatter class is used to create a pipe to display numbers in scientific notation, i.e. 1.237 x 10^3.  Other methods in this class are used to illustrate alternate displays using a non-piped implementation.

Custom pipes and validators will be part of the eventual Typescript Math Toolkit release, so the pipe is implemented in a separate class to facilitate re-use.  A reusable number validator is also injected into main component.

As with other demos, the UI is very basic.  After building the demo, enter a number into the input box and it is formatted in various ways on-the-fly.  Study the template and the component code to see both the pipe implementation as well as the benefits of the custom pipe approach.

pipe

For larger numbers, you may insert commas and for smaller numbers, you may experiment with rounding to the nearest tenth, half, or one.

As always, code is available at a friendly, neighborhood github near you.

Have fun!

Comments are closed.