omponentPipe’s are one of the important features of Angular. Angular comes with a stock of pre-built pipes such as Date Pipe, UpperCasePipe, LowerCasePipe, CurrencyPipe and PercentPipe and so many. Angular allows us to create our own pipe.
The syntax for creating a pipe in command prompt.
ionic -g pipe name-of-pipe-here
The pipe is a class whose sole purpose is to use a method to transform a given value or set of value. The pipe will help us to display in a different format without changing its value. We will create our own pipe with help of @Pipe decorator.
Screen shot of our app.
We this example we do not accept any value from the user, just for demo purpose we are using dummy data in our apps.
Step 1: ionic start CustomPipe blank
Step 2: Run following command to create pipe
ionic generate pipe custom
Step 3: Create a folder pipes inside app and move all generated pipe files in pipes folder. Add the following code in app/pipes/custom.pipe.ts file create a folder pipes inside app folder.
We have used transform(value:any, arg) is a method of Pipe class which will take two parameters first value is a value from the left side of | pipe symbol, in our case is user variable from home.ts as value and arg is the second argument is the right side of pipe |. To create a custom pipe in ionic we have to import Pipe and PipeTransform from the angular/core.
We will create another file pipes.module.ts inside pipes, will import all reference of pipe inside this pipe module. Some project may contain more than one pipe. Add the following code in app/pipes/pipes.module.ts file
In angular, we convert any value to any desired format with the help of an Angular pipe. Angular will detect the sign | as the pipe in the HTML or template and turns the value in front of it to input. If any reference to the pipe is created automatically in app.module.ts file while run pipe generates command, then you can remove it.
Step 3: Add the following code in home.ts, Is good practice to move all page into pages folder. Create a separate folder called pages in the app folder and move home page in the app folder. And we also have to add a page in front of route path in app-routing.module.ts
Step 4: Add the following code in home.html.
In-home template we have use user | userExtract : “firstname”, where a user is a variable object, userExtract is pipe name and first name is an argument to extract the first name from a user object
Step 5: In home.module.ts we have to add pipes module. Add the following code in home.module.ts file.