Angular Custom Pipe Usage

In Angular 2+, we can use custom pipes to format or convert data such as character (string), number or date in our .html templates.

In this example, we will write a custom pipe to remove the Lorem part of the text “Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,” and show the rest in the template.

First we create a ts file named new-custom.pipe.ts.

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

@Pipe({ name: 'newCustomPipe' })
export class newCustomPipe implements PipeTransform {
  constructor() {
  }

  public data:string=null;
  transform(value:string) :string {    //return string type
    this.data=value.substring(5);
    return this.data;
  }
}
// The simplest Custom Pipe example. We need to add it to declarations in Angular Module.

Then we define the custom pipe in app.module.ts

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

import { AppComponent } from './app.component';
import { newCustomPipe } from './new-custom.pipe.ts';

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

We use newCustomPipe in the template as follows;

<table class="row-border hover" >
  <thead>
    <tr>
      <th>#</th>
      <th>Description</th>
      <th>Time</th>
      <th>Student</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of sessions;let i = index">
      <td>{{ i + 1}}</td>
      <td>{{item?.description | newCustomPipe}}</td>
      <td>{{item?.time | date: 'dd/MM/yyyy HH:mm'}}</td>
      <td>{{item?.first_name}} {{item?.last_name}}</td>
    </tr>
  </tbody>
</table>

Custom Pipe with Argument

If we want to send argument from the template, we do it as follows;

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

@Pipe({ name: 'newCustomPipe' })
export class newCustomPipe implements PipeTransform {
  constructor() {
  }

  transform(value:string, before: string, after: string) :string {
    let newStr = `${before} ${value} ${after}`;
    return newStr;
  }
}
<td>{{item?.description | newCustomPipe :"Begining of line":"End of line"}}</td>

We learned how to create it in cases where we need to write custom pipes.

Success …