How do you create a custom pipe in Angular 4?
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 }}