1.

How do you create a custom pipe in Angular 4?

Answer»

Here’s an example of creating a pipe which reverses the order of letter WITHIN a string. Following is the code to be found in the reverse-str.pipe.ts file.

IMPORT { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'reverseStr'})
export class ReverseStr implements PipeTransform {
   transform(value: string): string {
      let newStr: string = "";
      for (VAR i = value.length - 1; i >= 0; i--) {
         newStr += value.charAt(i);
      }
      return newStr;
   }
}

Now, including the custom pipe as a declaration within the Angular app module:

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 { ReverseStr } from './reverse-str.pipe.ts';
@NgModule({
DECLARATIONS: [
   AppComponent,
   ReverseStr
],
imports: [
   BrowserModule,
   FormsModule,
   HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Here’s how to use the custom pipe in your TEMPLATES:

{{ user.name | reverseStr }}



Discussion

No Comment Found