Angular Pipes

In this weeks blog post I will be taking another look at Angular and more specifically Custom Pipes in Angular. While Angular has many built in Pipes ready for use, we would like to extend our applications by creating custom pipes for our applications. Custom pipes allow the developer to create a pure function that can accept an input and return a different output. This is done through a transformation within the pipe.

In order to use Pipes in general they must be imported from the Angular core library. In this example, we are looking to convert a file size of 2120109 into a more readable format of something such as 2.5MB. After importing the Pipe library, we must create a class for the pipe and give it a name as seen in the code below. In order to name the pipe (in example seen as “filesize”) we must use the Typescript decorator @Pipe and provide a name that matches the template code name. The pipe must also be registered in your @NGModule under declarations.

Screenshot (24)

After the class is setup, it is time to implement the PipeTransform interface. The interface creates a required contract that the FileSizePipe adheres to. Since the Pipe is being used via interpolation, the file.size variable is passed through the transform method as the first argument. This is used to convert the numeric value into a readable form. The FileSizePipe method transformed the digits into a string and appends ‘MB’ at the end to make it more readable.

Screenshot (25)

In order to make this a custom pipe, the example  adds the capability for an extension to the code. Using a default parameter instead of appending the ‘MB’ to the end of the string which allows us to use the default ‘MB’ or override it when necessary. This must be passed as an argument into the pipe as seen below.

Screenshot (26)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s