Angular 2 pure and impure pipes

When to use pure and impure Pipes?

In Angular 2, there are two types of pipes i.e.
1.      pure
2.      impure

The pure pipe is by default. Every pipe has been pure by default. If you want to make a pipe impure that time you will allow the setting pure flag to false.

Stayed Informed What is Pipes?

Pure Pipes:-
Angular executes a pure pipe only when it detects a pure change to the input value. A pure change can be primitive or non-primitive.

Primitive data are only single values, they have not special capabilities and the non-primitive data types are used to store the group of values.

For example for pipe pure,
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'barcode'
})
export class BarCodePipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if (!value) {
            return '';
        }
        return "****-****_" + (value.length > 8 ? (value.length - 8): '')
    }
}

Impure Pipes:-
Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move. 

If you want to make a pipe impure that time you will allow the setting pure flag to false.

For example for pipe impure,
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'barcode',
    pure: false
})
export class BarCodePipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if (!value) {
            return '';
        }
        return "****-****_" + (value.length > 8 ? (value.length - 8): '')
    }
}

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^