askvity

How to Create a Filter in Angular?

Published in Angular Development 4 mins read

Creating a filter in Angular involves registering a new filter with your Angular module, which then can be used to transform data in your templates or components. Here's a step-by-step guide:

Steps to Create a Filter in Angular

  1. Create an Angular Application: (If you don't have one already. This part is more about setting up an Angular project rather than creating the filter itself.)

  2. Define the Filter: You'll use the .filter API provided by Angular to register your custom filter with your Angular module. This involves providing a name for your filter and a filter function.

  3. Implement the Filter Function: The filter function takes the input value as an argument and returns the transformed value. This is where you implement the specific logic for your filter.

Code Example (AngularJS)

This is the older AngularJS way to define filters. Note the difference from Angular (2+) shown later.

// Create a module
var app = angular.module('myApp', []);

// Register a filter
app.filter('myCustomFilter', function() {
  // Filter function
  return function(input) {
    // Logic to transform the input
    if (!input) {
      return '';
    }
    var output = input.toUpperCase(); // Example: convert to uppercase
    return output;
  };
});

Explanation:

  • angular.module('myApp', []): Creates or gets the Angular module named 'myApp'.
  • app.filter('myCustomFilter', function() { ... });: Registers a filter named 'myCustomFilter' with the module.
  • return function(input) { ... };: This inner function is the actual filter logic. It takes the input value and returns the transformed output.
  • input.toUpperCase(): This is example logic to convert the input string to uppercase.

Using the Filter in HTML (AngularJS)

<div ng-app="myApp" ng-controller="myController">
  <input type="text" ng-model="myText">
  <p>Original Text: {{ myText }}</p>
  <p>Filtered Text: {{ myText | myCustomFilter }}</p>
</div>

<script>
  angular.module('myApp').controller('myController', function($scope) {
    $scope.myText = "hello world";
  });
</script>

Explanation:

  • {{ myText | myCustomFilter }}: This applies the 'myCustomFilter' to the value of myText before displaying it. The | symbol is the pipe operator used to apply filters.

Angular (2+) - Using Pipes (Filters)

In Angular (versions 2 and later), filters are called Pipes. Here's how to create and use one:

// my-custom.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'myCustomPipe'
})
export class MyCustomPipe implements PipeTransform {
  transform(value: any, ...args: any[]): any {
    if (!value) {
      return '';
    }
    return value.toUpperCase(); // Example: Convert to uppercase
  }
}

Explanation:

  • @Pipe({ name: 'myCustomPipe' }): This decorator registers the pipe with the name myCustomPipe.
  • PipeTransform: This interface is implemented to define the transform method.
  • transform(value: any, ...args: any[]): This is the pipe's logic. It takes the input value and any optional arguments (...args).
  • value.toUpperCase(): This is example logic to convert the input string to uppercase.

Using the Pipe in a Component (Angular 2+)

  1. Import and Declare the Pipe: Make sure to import the pipe in your module and declare it in the declarations array.

    // app.module.ts
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { MyCustomPipe } from './my-custom.pipe';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [
        AppComponent,
        MyCustomPipe // Declare the pipe
      ],
      imports: [
        BrowserModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
  2. Use the Pipe in the Template:

    <!-- app.component.html -->
    <div>
      <input type="text" [(ngModel)]="myText">
      <p>Original Text: {{ myText }}</p>
      <p>Filtered Text: {{ myText | myCustomPipe }}</p>
    </div>
    // app.component.ts
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      myText: string = "hello world";
    }

Key Differences Between AngularJS Filters and Angular Pipes:

  • Syntax: AngularJS uses app.filter() to define filters, while Angular uses @Pipe decorator and PipeTransform interface.
  • Arguments: Angular Pipes can accept multiple arguments in the transform method, providing more flexibility.
  • TypeScript: Angular pipes benefit from TypeScript's type safety.

In summary, creating a filter (or pipe) in Angular allows you to transform data for display purposes, enhancing the presentation and user experience. Choose the appropriate method based on whether you are using AngularJS or a more recent version of Angular.

Related Articles