Angular 2 Custom Pipe


Angular 2 Custom Pipe

We can create a custom pipe in Angular based on our requirement like if you would like to capitalize the first letter of each word.

Let’s create one Angular custom pipe to capitalize the first character of each word.

Example

  1. camel-case.pipe.ts
  2. app.module.ts  – Now we can make it globally available by updating into this any main Module.
  3. customer.html

camel-case.pipe.ts

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

@Pipe({ name: 'camelcase' })
export class CamelCasePipe implements PipeTransform {
 transform(value: string):any {
   if (value == null) {
     return value;
   } else {
      return value.replace(/\w\S*/g, function (txt) {
      value = txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
      return value;
   });
  }
 }
}

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 { CamelCasePipe } from './customer/camel-case.pipe';

@NgModule({
declarations: [
  AppComponent,
  CamelCasePipe
],
imports: [
  BrowserModule,
  FormsModule
],
exports:[
   CamelCasePipe
],
 providers: [],
 bootstrap: [AppComponent]
})

export class AppModule { }

customer.html

<h1>{{firstName | camelcase}}</h1>

 






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229