English 中文(简体)
Angular 2 - Custom Pipes
  • 时间:2024-11-03

Angular 2 - Custom Pipes


Previous Page Next Page  

Angular 2 also has the facipty to create custom pipes. The general way to define a custom pipe is as follows.

import { Pipe, PipeTransform } from  @angular/core ;  
@Pipe({name:  Pipename }) 

export class Pipeclass implements PipeTransform { 
   transform(parameters): returntype { } 
} 

Where,

    Pipename − This is the name of the pipe.

    Pipeclass − This is name of the class assigned to the custom pipe.

    Transform − This is the function to work with the pipe.

    Parameters − This are the parameters which are passed to the pipe.

    Returntype − This is the return type of the pipe.

Let’s create a custom pipe that multippes 2 numbers. We will then use that pipe in our component class.

Step 1 − First, create a file called multipper.pipe.ts.

Multipper

Step 2 − Place the following code in the above created file.

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

@Pipe ({ 
   name:  Multipper  
}) 

export class MultipperPipe implements PipeTransform { 
   transform(value: number, multiply: string): number { 
      let mul = parseFloat(multiply); 
      return mul * value 
   } 
} 

Following points need to be noted about the above code.

    We are first importing the Pipe and PipeTransform modules.

    Then, we are creating a Pipe with the name Multipper .

    Creating a class called MultipperPipe that implements the PipeTransform module.

    The transform function will then take in the value and multiple parameter and output the multippcation of both numbers.

Step 3 − In the app.component.ts file, place the following code.

import { 
   Component 
} from  @angular/core ;  

@Component ({ 
   selector:  my-app , 
   template:  <p>Multipper: {{2 | Multipper: 10}}</p>  
}) 
export class AppComponent {  } 

Note − In our template, we use our new custom pipe.

Step 4 − Ensure the following code is placed in the app.module.ts file.

import {
   NgModule
} from  @angular/core ;

import {
   BrowserModule
} from  @angular/platform-browser ;

import {
   AppComponent
} from  ./app.component ;

import {
   MultipperPipe
} from  ./multipper.pipe 

@NgModule ({
   imports: [BrowserModule],
   declarations: [AppComponent, MultipperPipe],
   bootstrap: [AppComponent]
})

export class AppModule {}

Following things need to be noted about the above code.

    We need to ensure to include our MultipperPipe module.

    We also need to ensure it is included in the declarations section.

Once you save all the code changes and refresh the browser, you will get the following output.

Multipper Output Advertisements