Angular 2 — Using Pipes in Classes

Warning: This was written for Angular2 RC4. The majority of it is still valid, however pipes used within template logic should now be declared as part of a module and not a component as done here.

Angular 1 $filters are easy to use regardless of whether it was template or controller you wanted to use them. Angular 2 has replaced $filters with Pipes, which are essentially the same concept. They are applied in templates the same way as $filters, using a pipe (|).

Custom Pipes are declared in the same manner as components and services, using the Pipe decorator. This is where the Pipe’s name is specified and should match the Pipe’s class name.

The transform method is where the magic happens. This needs to be imported and implemented with the Pipe’s class. Angular will use this method for evaluating values when the Pipe is applied in a component’s template. You don’t have to call this method yourself, Angular takes care of it.

The first argument is the value the Pipe is being applied too. Further arguments are parameters that can be used for additional configuration. These arguments are passed (and separated) using a colon when the Pipe is applied in the template e.g. {{ ‘hello world’ | capitalize:true }}.

The Pipe can be used inside a component’s class too. First it needs to be instantiated. Unlike template usage however, the transform method must be called directly with the correct parameters being passed.

The example below demonstrates a Pipe being used in a component’s template and class.t

A single golf clap? Or a long standing ovation?

By clapping more or less, you can signal to us which stories really stand out.