Angular 2 Custom Pipe Example Typescript

In this example, we will be creating two custom pipes in Angular 2 using Typescript and also chain them up. For Javascript implementation, please see Angular 2 Custom Pipe Example Javascript

  • translate – a stateful pipe that retrieves a bundle from service and translate the given value using the bundle
  • nvl – a stateless pipe. Just like the Oracle NVL function, it returns the given string if there is no value

 

Source code of this example is available here.

 

Folder

Angular 2 Custom Pipe Example Typescript folder

bundle.json

This is the message bundle that will be used by the translate pipe.

message.service.ts

This is the service that retrieves the bundle and will be used by the filter.

translate.pipe.ts

This is a stateful pipe that retrieves a message bundle and translate the given value using the bundle.

nvl.pipe.ts

This is a stateless pipe that works just like the Oracle NVL function. In case you don’t know, it returns the given string as default value if there is no value.

app.component.ts

This is the root component of this example. In order to use the custom pipes, we need to register them to the component as show below. By the way, all built-in pipes are pre-registered.

app.component.tpl.html

Here is where we use the custom pipes. As you can see, we chain the 2 pipes up and also tell the nvl pipe to return N/A  as default value if there is not input value or the bundle doesn’t know about the input value.

boot.ts

And we configure the bootstrap like this.

index.html

Result

When keyed in ‘2’, according to the bundle.json, word “two” is returned.
Angular 2 Custom Pipe Example Typescript result 1

When keyed in “one”, according to the bundle.json, number 1 is returned.

Angular 2 Custom Pipe Example Typescript result 2

when keyed in “test”, “N/A” is returned from nvl pipe as the bundle.json doesn’t know about it.

Angular 2 Custom Pipe Example Typescript result 3

 

Resources

 


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.