This is a post meant to help you understand pipes in Angular 2, and what better place to start than the simplest pipe possible? :)
From Filters To Pipes
If you're familiar with AngularJS then you might be wondering why there are no filters in Angular 2. Well, you can pretty much think of pipes as the Angular 2 equivalent for filters. Although creating each uses a different syntax, they provide the same purpose; to transform data in the view while preserving the data in it's original form. For example, the currency filter allows you to work with pure numbers that can be combined with ordinary mathematical operations while at the same time displaying the data in a nice format with a currency symbol and at most only 2 digits past the decimal.
Angular CLI Pipe Scaffolding
If you're using the Angular CLI you can scaffold out a stub for a pipe super easily with the generate command (shorthand is just g):
This will generate a file named derpy-derp.pipe.ts (and also a unit test file named derp-derp.spec.ts) in the app/ directory. You could also prefix the name "derpy-derp" with folder names and slashes in order to generate your files further down in your directories. This command will generate some boilerplate code for a pipe that should look something like this:
The above code is what's generated by the Angular CLI, but a pipe that just returns null is no fun. Let's instead have it return something simple, like the number 42!
Using A Pipe In Your Template
In the HTML markup we can make use of this pipe. Normally we're going to want to transform some dynamic piece of data that is represented by a variable in our component. Inside our our Angular 2 data-binding double curlies we can add the pipe symbol followed by our pipe's name:
We can also pass arguments to our pipe like so:
And then we can reference these arguments in our pipe's transform method like this:
Using Your Pipe In The TypeScript
The posts on this site are written and maintained by Jim Lynch. About Jim...