How to make a custom pipe in angular? In 3 steps.
Complete guide to starting making custom Angular Pipe. We will create a pipe that will replace ‘,’ with ‘-’ in a string.
Introduction
Angular Pipe is a simple way to transform values, A pipe takes in a value or values and then returns a value. This is great for simple transformations on data but it can also be used in other unique ways.
Let's start our Custom Pipe
Angular provides the feature to implement a custom pipe by implementing the interface of PipeTransform.
We are going to build a pipe that will replace the ‘,’ sign within the string with the 5 commas.
Step 1: Create a custom pipe file: customPipe.ts
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "CommaToHyphen"
})
export class CommaToHyphenPipe implements PipeTransform {
transform(value: string, numberTime: number): string {
let n = value;
let separator = ''
for(let i = 0; i < numberTime ; i++) separator += '-'
return n.split(",").join(separator);
}
}
Step 2: Importing the Custom Pipe to app.module.ts
import { NgModule } from “@angular/core”;
import { BrowserModule } from “@angular/platform-browser”;
import { FormsModule } from “@angular/forms”;
import { AppComponent } from “./app.component”;
import { CommaToHyphenPipe } from “./customPipe”;
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, CommaToHyphenPipe],
bootstrap: [AppComponent]
})
export class AppModule {}
Step 3: Use it
app.component.tsimport { Component, VERSION } from “@angular/core”;
@Component({
selector: “my-app”,
templateUrl: “./app.component.html”,
styleUrls: [“./app.component.css”]
})
export class AppComponent {
randomString = “Manan,Tusar”;
}app.component.html
{{randomString | CommaToHyphen: 1}}
<br>
{{randomString | CommaToHyphen: 5}}
<br>
{{randomString | CommaToHyphen: 10}}Output
Manan-Tusar
Manan-----Tusar
Manan----------Tusar
Some built-in Pipe
- Currency: currency
component.ts
this.a = 10component.html:
{{a | currency}}Output:
$10
2. Data and Time: date
component.ts:
this.today = new Date()component.html:
{{today | date:'short'}}Output:
6/15/15, 9:03 AM
Conclusion
Angular Pipe is very useful and can help you to make custom transform to string or number with the clean structure of the project.