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.
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.
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.
https://toddmotto.com/angular-pipes-custom-pipes
From the blog CS@Worcester – Jarrett's Computer Science Blog by stonecsblog and used with permission of the author. All other rights reserved by the author.