What is pipe in angular - amresh087/newronaRepos GitHub Wiki
In Angular, the @Pipe decorator is used to define a custom pipe, which is a way to transform data in templates. Pipes are a convenient way to format or transform data displayed in your application. Here’s a detailed explanation of how to create and use a custom pipe using the @Pipe decorator:
Import the Necessary Modules: You need to import Pipe and PipeTransform from @angular/core.
Define the Pipe Class: The class should implement the PipeTransform interface, which requires you to define a transform method.
Use the @Pipe Decorator: This decorator is used to specify the name of the pipe and any additional metadata.
Here’s an example of a simple custom pipe that converts text to uppercase:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
To use the custom pipe in a template, you need to declare it in an Angular module and then apply it in the template:
Declare the Pipe in a Module: Add the custom pipe to the declarations array of your module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { UppercasePipe } from './uppercase.pipe';
@NgModule({
declarations: [
AppComponent,
UppercasePipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Apply the Pipe in a Template: Use the pipe in the template with the pipe symbol (|)
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div>{{ 'hello world' | uppercase }}</div>`
})
export class AppComponent { }
Pipes can also accept parameters to customize their behavior. Here’s an example of a pipe that formats a number to a specified number of decimal places:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'decimal'
})
export class DecimalPipe implements PipeTransform {
transform(value: number, decimalPlaces: number): string {
return value.toFixed(decimalPlaces);
}
}
Declare the pipe in a module and use it in a template with parameters:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { DecimalPipe } from './decimal.pipe';
@NgModule({
declarations: [
AppComponent,
DecimalPipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
//component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<div>{{ 1234.56789 | decimal:2 }}</div>`
})
export class AppComponent { }