Create custom pipe in Angular

Create custom pipe in Angular

In angular pipes are used to transform strings, currency amounts, dates, and other data for display. Pipes are simple functions you can use in template expressions to accept an input value and return a transformed value. Pipes are useful because we declare each pipe once and we can use them throughout our application. There is some default pipe in angular but some times we need a custom pipe to format our data. Today we build a custom pipe with Regex, let’s build :)

Start with a new angular application,

ng new CustomPipe

Now we create a pipe with angular CLI named SliceUpper,

ng generate pipe SliceUpper

Our custom pipe

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

  name: 'SliceUpper'
export class SliceUpperPipe implements PipeTransform {

  transform(val: string): string {
    return val.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toUpperCase();


Our generated class SliceUpperPipe implements PipeTransform and the transform method accepts a string parameter and returns a string, in this method we use a Regex to split a string on a camel case and turn it into an upper case.

Import our custom pipe in app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SliceUpperPipe } from './slice-upper.pipe';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Now we use our pipe in our component, out app.component.ts file,

import { Component } from '@angular/core';
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'CustomPipe';

  valueList: string[] = ['userName', 'userFirstName', 'userLastName', 'email']

This is our app.component.ts with a list of camel case strings which will be formated with our custom pipe SliceUpper. In app.component.html we use SliceUpper pipe to formate data and this is the output of our pipe.

our app.component.html file,

  <div *ngFor="let item of valueList">
    <h5>{{item | SliceUpper}}</h5>

Owwww! our output is here,


Thank you :)

GitHub Link: