In this tutorial we are going to create a custom angular pipe and see how they can be useful in transforming the data on the template. There are different pipes for different type of template output and we can create a one of our own depending on the requirement.
Create the Angular Pipe file using CLI
Use the command ng generate pipe custom-pipe to create the boilerplate code for the pipe. Notice in the code below that the class must implement the PipeTransform interface which resides in ‘@angular/core’ and its transform method.
It also has a decorator named @Pipe which specifies the name which will be used to apply the pipe.
The transform method except some parameter first of which is mandatory and is the value on which the pipe transformation needs to be applied. Any parameters which you need to pass are the additional parameters here.
The method return a new string or the modified string post the custom operation performed on it. Here we are going to trim the content and return just first 30 charters of it. And then in the next step we will add a parameters which allows us to select the character count to return.
Also Read: Routing in Angular 8
Now let us update our transform method to get the sub string.
Use the Angular Pipe
In the app.component.html file let us now add a long paragraph text and use our demopipe.
We will use the built in substr method to get the first 30 characters and just add three dots “…” in the end.
Pass Parameter to Custom Pipe
Let us now give the capability to our pipe to accept the length of sub-string we want it to return. We do this by adding a parameter named length in our custom pipe and then passing the desired value post “:” in the html component.
Now we can check the browser to see the difference with and without the angular pipe.
You can refer the official documentation to know more about the built in pipes in angular.