In Angular1, filters are used which are later called Pipes onwards Angular2. In Angular7, it is known as pipe and used to transform data. It is denoted by symbol |
Pipe takes integers, strings, arrays, and date as input separated with |. It transforms the data in the format as required and displays the same in the browser.
Let's see an example using pipes. Here, we display the title text in upper and lower case by using pipes.
Define a variable named "title" in component.ts file.
Use the pipe symbol in component.html file:
Run ng serve and see the result. You will see the following result.
Here, you can see that pipes have changed the tittle in upper and lowercase.
Angular7 Built-in Pipes
Angular7 provides some built-in pipes:
You have seen the lowercasepipe and uppercasepipe examples. Now, let's take some examples to see how the other pipes work.
Define the required variables in component.ts file.
Use the different built-in pipe symbols in component.html file:
You can see the use of all built-in pipes here:
How to create a custom pipe?
To create a custom pipe, create a new ts file and use the code according to the work you have to do. You have to import Pipe, PipeTransform from Angular/Core. Let's create a sqrt custom pipe.
Now, it's turn to make changes in the app.module.ts. Create a class named as SqrtPipe. This class will implement the PipeTransform. The transform method defined in the class will take argument as the number and will return the number after taking the square root.
As, we have created a new file so, we need to add the same in app.module.ts.
Now, use sqrt pipe in component.html file.