Angular pipes are very useful for formatting and transforming data right inside templates. Angular comes with pipes for dates, currency, character cases and percentage. They are all available for use in any template. But there are situations where you need a custom solution. Angular lets you easily define custom pipes of your own.

We will start with an example custom pipe that takes a string and capitalize the first letter. Create a new file called capitalize-pipe.ts inside your app folder and copy the following code inside it:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'capitalize'})
export class CapitalizePipe implements PipeTransform {

  transform(value: any) {
    if (value) {
      return value.charAt(0).toUpperCase() + value.slice(1);
    }
    return value;
  }

}

Then you need to include this custom pipe in declaration array of app.module.ts so that it is available to all templates:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { CaptializePipe } from './capitalize.pipe.ts';

@NgModule({
  declarations: [
    AppComponent,
    CaptializePipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now you can use this pipe in your components (or templates) as following:

import { Component } from '@angular/core';

@Component({
  selector: 'app-user',
  template: `
    <h2>{{user.name | capitalize}}</h2>
  `
})
export class UserComponent { }

Pipes with parameters

A pipe can accept any number of optional parameters to format its output. You can also define custom pipes with multiple parameters. For example, here is a pipe that takes two strings and concatenates them:

@Pipe({name: 'concatenate'})
export class ConcatenatePipe implements PipeTransform {
  transform(str1: string, str2: string): string {
    return str1 + ' ' + str2;
  }
}

It can be used in templates as following:

{{ 'Hello' | concatenate:'World!' }} // will output Hello World!

If you want to learn more about Angular pipes, checkout Angular official documentation for pipes which explains pipes in details.

Don't forget to subscribe to our Weekly Design newsletter to get weekly recap of best design articles, resources and jobs every Monday 10am. Find this article useful? Share it with your friends and followers below.