Rachid O
Rachid O

Reputation: 14052

When to use a pipe in Angular

Is there any rule, or best practice to tell when a pipe is best over a component method ?

Maybe something like, when something is purly a view logic and doesn't contain any domain logic

Upvotes: 0

Views: 314

Answers (3)

Sina Lotfi
Sina Lotfi

Reputation: 3284

A Pipe takes in data as Input and Transforms it to a desired Output.

For example, in most use cases, users prefer to see a Date in a simple format like April 15, 1988 rather than the raw string format Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time), this format for showing just birth date is ugly and you can beatify this by Pipes.

Fri Apr 15 1988 00:00:00 GMT-0700 convert to April 15, 1988

Upvotes: 0

Haifeng Zhang
Haifeng Zhang

Reputation: 31915

Quote from Angular Best Practices — August 2017 Edition

One scenario is usually we subscribe to Observables and get the values when it is ready.

...
template: `
    {{myData | json}}
`)
export class XXXComponent {
    myData;
    constructor(http: HttpClient) {
        http.get('path/to/my/data/api.json')
        .subscribe(data => {
            this.myData = data;
        });
    }
}

The better way is using async pip within template and let Angular manage the lifecycle for us. The Async pipe will cancel HTTP requests if the data is no longer needed, instead of completing, processing, and then doing nothing with it.

...
template: `
    {{data | async | json}}
`)
export class XXXComponent {
    data;
    constructor(http: HttpClient) {
        this.data = http.get('path/to/my/api.json');
    }
}

Most cases pipe are used for transforming data, one of the advantages is it is simple AND it is chaining! You can do a lot of combinations based on your specific requirements and each pipe can be reused. <p>{{ myArray | slice:0:2 | json }}</p>

Upvotes: 0

Taras Ilyin
Taras Ilyin

Reputation: 101

Basically you should consider using pipe when some data requires some transformation in your template and you don't want to have a "dirty logic" in your component code.

For example, imagine you getting some html string from server or whatever. And you need to display this string in your template, but you want to display it as a plan text (simple string) without any html tags.

In this case this would be a good to create a pipe for that:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'htmlToPlanText'
})
export class HtmlToPlanTextPipe implements PipeTransform {
    transform(value: string) {
        let html = new String(value);
        return html.replace(/(\<(\/?[^>]+)>)/g, '');
    }
}

end next you can use it in your template code in this way:

<span>{{yourHtmlString | htmlToPlanText}}</span>

This will transform your html string to plan text.

Please note, this will note change your original variable in component controller. It will just transform value when rendering your component template.

Upvotes: 2

Related Questions