All about pipe in angular 9 for dummies (custom pipe | pure | impure pipes)
All about pipe in angular 5 for dummies (custom pipe | pure | impure pipes)
We can create our custom pipes with the below steps:
- Create the typescript class with @Pipe decorator
2. Provide the name of the pipe to the @Pipe decorator’s name property.
3. Implement the class with PipeTransform
4. Provide the implementation of the pipe functionality inside the transform method.
5. transform is the method need to be used for any custom pipes and the same needs to return something.
6. Once the custom pipe is created then we need to add it to our app module. (app.module.ts file)
7. Then it can be used in any templates
Eg: Now I am going to create the simple pipe to make the first letter alone to capital.
[html]
@Pipe({name:’FirstCap’})
export class FirstLetterCapPipe implements PipeTransform {
transform(value:any){
// logic to return the received input with first letter alone to capital
}
}
[/html]
And use it in the templates like this,
[html]
<div class=”container”>
{{ hello | FirstCap}}
</div>
[/html]
Now the expected output would be,
[plain]
Hello
[/plain]
Creating the parameterized custom pipe:
If suppose you want to receive the parameter to your transform method then the same can be passed from your template file like this,
[html]
<div class=”container”>
{{ hello | FirstCap : ‘all’ }}
</div>
[/html]
Here ‘all’ is the parameter passed from the template, this can be used in our transform method to make all the letters/words to capital instead of making only the first letter capital,
[html]
@Pipe({name:’FirstCap’})
export class FirstLetterCapPipe implements PipeTransform {
transform(value:any, param:string){
// logic to return the received input with first letter alone to capital
// now we received param as well from the template
}
}
[/html]
Then need to pass the parameter from template after : (colon) ,
[html]
<div class=”container”>
{{ hello | FirstCap : ‘all’ }}
</div>
[/html]
Now we will get,
[plain]HELLO[/plain]
What is pure and impure pipes ?
By default all the built in angular pipes are pure, if we want to change our custom pipe to impure then we can use pipe:false property of @Pipe decoration.
[html]
@Pipe({name:’FirstCap’,pure:false})
export class FirstLetterCapPipe implements PipeTransform {
transform(value:any, param:string){
// logic to return the received input with first letter alone to capital
// now we received param as well from the template
}
}
[/html]
Now our pipe becomes impure pipe and it runs for every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.
Impure are bad comparing to pure pipes respect to the performance as it runs so often on change detection cycle.