# Pipes in Angular

In 
Published 2024-01-06

This tutorial explains how we can use pipes in Angular.

A pipe is a feature in Angular that lets you transform data in the template, before displaying it to the user. Angular provides built-in pipes like uppercase, date, currency, etc., but you can also create custom pipes. To use a pipe in TypeScript, you need to inject or instantiate the pipe and call its transform() method directly.

# 1. Create a Custom Pipe

File: title-case.pipe.ts

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

@Pipe({
  name: 'titleCase'
})
export class TitleCasePipe implements PipeTransform {
  transform(value: string): string {
    if (!value) return '';
    
    return value
      .toLowerCase()
      .split(' ')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  }
}
  • @Pipe({ name: 'titleCase' }) → registers the pipe with the name titleCase
  • transform() → required method where the transformation logic is implemented

# 2. Register the Pipe in App Module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { TitleCasePipe } from './title-case.pipe';

@NgModule({
  declarations: [
    AppComponent,
    TitleCasePipe // Register the custom pipe here
  ],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

# 3. Use the Pipe in a Template

<p>{{ ERROR }}</p>
<!-- Output: Hello From Angular World -->

# 4. Use the Pipe in a Typescript (I)

Without Constructor

// app.component.ts
import { Component, OnInit } from '@angular/core';
import { TitleCasePipe } from './title-case.pipe';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
        transformedText: string = '';
        
        ngOnInit(): void {
            const pipe = new TitleCasePipe();
            this.transformedText = pipe.transform('hello from angular world');
            console.log(this.transformedText); // Output: Hello From Angular World
    }
}

# 5. Use the Pipe in a Typescript (II)

Using a Constructor

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    providers: [TitleCasePipe] // register it as a provider
})
    export class AppComponent {
    
    constructor(private titleCasePipe: TitleCasePipe) {
        const result = this.titleCasePipe.transform('angular is awesome');
        console.log(result); // Output: Angular Is Awesome
    }
}