All about pipe in angular 5 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:

  1. 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.


@Pipe({name:'FirstCap'})
export class FirstLetterCapPipe implements PipeTransform {

transform(value:any){
// logic to return the received input with first letter alone to capital
}

}

 

And use it in the templates like this,


<div class="container">
{{ hello | FirstCap}}
</div>

Now the expected output would be,


Hello

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,

<div class="container">
{{ hello | FirstCap : 'all' }}
</div>

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,

 


@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
}

}

Then need to pass the parameter from template after : (colon) ,


<div class="container">
{{ hello | FirstCap : 'all' }}
</div>

 

 

Now we will get,

HELLO

 

 

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.


@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
}

}

 

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.

 

193 total views, 2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *