How to create custom pipe in angular

Author
April 06, 2022

In this article i will explain you how you can create custom pipe in angular application, i will create a custom pipe text shortener.

Step 1: Create a file for your custom pipe and add it to your module

  • Create a file named as shorten.pipe.ts or whatever name that is suitable to you in your component folder or a separate folder /src/pipe

  • Add the following code in to your src/pipe/shorten.pipe.ts

//src/pipe/shorten.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "shorten",
})
export class ShortenPipe implements PipeTransform {
  transform(value: any, limit: number) {
    if (value.length > limit) {
      return value.substr(0, limit) + " ...";
    }
    return value;
  }
}
  • Declare the pipe which you have just created in your src/app.module.ts
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";
import { ShortenPipe } from "./shorten.pipe";
import { FilterPipe } from "./filter.pipe";

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

Step 2: Using the pipe

Once you have followed all the steps above you can use this custom pipe for example

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <input type="text" [(ngModel)]="filteredStatus" />
      <br />
      <button class="btn btn-primary" (click)="onAddServer()">
        Add Server
      </button>
      <br /><br />
      <h2>App Status: {{ appStatus | async}}</h2>
      <hr />
      <ul class="list-group">
        <li
          class="list-group-item"
          *ngFor="let server of servers | filter:filteredStatus:'status'"
          [ngClass]="getStatusClasses(server)"
        >
          <span class="badge"> {{ server.status }} </span>
          <!-- Custom pipe used here with name shorten and parameter passed is 15  -->
          <strong>{{ server.name | shorten:15 }}</strong> | {{
          server.instanceType | uppercase }} | {{ server.started |
          date:'fullDate' | uppercase }}
        </li>
      </ul>
    </div>
  </div>
</div>