Angular 13 Filter Data List using Custom Pipe

In this tutorial, you will learn how to filter a list of items using a custom Pipe in the Angular application. We will add an input form control using which a user can enter a term, based on the search term the list of items will be filtered out to show matched items. Angular provides…

By.

•

min read

In this tutorial, you will learn how to filter a list of items using a custom Pipe in the Angular application.

We will add an input form control using which a user can enter a term, based on the search term the list of items will be filtered out to show matched items.

Angular provides a number of built-in pipes for various operations:

PIPES DETAILS
DatePipe Formats a date value according to locale rules.
UpperCasePipe Transforms text to all upper case.
LowerCasePipe Transforms text to all lower case.
CurrencyPipe Transforms a number to a currency string, formatted according to locale rules.
DecimalPipe Transforms a number into a string with a decimal point, formatted according to locale rules.
PercentPipe Transforms a number to a percentage string, formatted according to locale rules.

 

In our tutorial, we will learn how to create our own pipe, which will be used to filter the data items.

How to filter data items using Filter Pipe in Angular?

Follow these quick steps to create a custom pipe to filter the list created from a JSON object.

Step 1) Add FormsModule

Step 2) Create a Filter Pipe

Step 3) Declare FilterPipe in AppModule

Step 4) Update Template HTML

Step 5) Update Component Class

 

Step 1) Add FormsModule

In our app, we will use the Input form control with ngModel, so we need to import the FormsModule to use it in our application. Open the app.module.ts file and add the FormsModule in the imports array:

import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
     AppComponent
   ],
  imports: [
    BrowserModule,
    FormsModule //< -- Added here
    ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

 

Step 2) Create a Filter Pipe

Next, create a new Filter Pipe inside the pipes folder. You can execute the following ng generate command to create it for you:

ng generate pipe pipes/filter

Afterwards, update the pipe file ~app\pipes\filter.pipe.ts with the following content:

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

@Pipe({
  name: 'filter',
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items) return [];
    if (!searchText) return items;

    searchText = searchText.toLowerCase();
    return items.filter((it) => {
      return it.name.toLowerCase().includes(searchText);
    });
  }
}

Step 3) Declare FilterPipe in AppModule

To use our FilterPipe, we need to declare it inside the app.module.ts file. Open the AppModule and update the declarations array as shown below:

import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { FilterPipe } from './pipes/filter.pipe';

@NgModule({
  declarations: [
    AppComponent,
    FilterPipe, //< -- Added here
  ],
  imports: [
    BrowserModule, 
    FormsModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

 

Step 4) Update Template HTML

Now open the app.component.html file to add the Input control and ngFor loop that will iterate our JSON object to display the filter data list.

Update the app.component.html file with following content:

<div>
  <!-- Heading Title -->
  <h4 class="app-heading">Select Available Games Below:</h4>

  <!-- Search Field -->
  <div>
    <div class="filter-wrap">
      <input [(ngModel)]="searchText" placeholder="Filter Games" class="filter-input">
      <span class="filter-clear" *ngIf="searchText.length>0" (click)="clearFilter()">X</span>
    </div>
  </div>
  <!-- Clear Link -->
  <div class="clear-selection" title="Click to Clear Selections" (click)="clearSelection()" *ngIf="selected_count">Clear
    Selection</div>

  <!-- Game List -->
  <ul class="game-list">
    <li *ngFor="let g of games | filter : searchText" class="game-item">
      <input (change)="getSelected()" type="checkbox" name="games" value="{{g.id}}" [(ngModel)]="g.selected" />
      <span class="game-text">{{g.name}}</span>
    </li>
  </ul>

  <!-- Selected Games-->
  <div class="selected-games-wrap">
    <div class="selected-game" *ngFor="let s of selected_games">
      <span>{{s.name}} <span class="delete-game" (click)="deleteGame(s.id)" title="Click to delete">X</span></span>
    </div>
  </div>

</div>

Step 5) Update Component Class

Lastly, open the class component to add the various action methods to clear, check uncheck items etc.

Open the app.component.ts file and update it with the following code:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  searchText: string = '';
  selected_count: number = 0;
  selected_games: any;

  // Data Object to List Games
  games = [
    {
      name: 'Chess',
      id: 1,
      selected: true,
    },
    {
      name: 'Ludo',
      id: 2,
      selected: false,
    },
    {
      name: 'Snakes & Ladders',
      id: 3,
      selected: false,
    },
    {
      name: 'Carrom',
      id: 4,
      selected: false,
    },
    {
      name: 'Scrabble',
      id: 5,
      selected: false,
    },
    {
      name: 'Monopoly',
      id: 6,
      selected: true,
    },
    {
      name: 'Uno',
      id: 7,
      selected: false,
    },
  ];

  constructor() {
    this.getSelected();
  }

  // Getting Selected Games and Count
  getSelected() {
    this.selected_games = this.games.filter((s) => {
      return s.selected;
    });
    this.selected_count = this.selected_games.length;
    //alert(this.selected_games);
  }

  // Clearing All Selections
  clearSelection() {
    this.searchText = '';
    this.games = this.games.filter((g) => {
      g.selected = false;
      return true;
    });
    this.getSelected();
  }

  //Delete Single Listed Game Tag
  deleteGame(id: number) {
    this.searchText = '';
    this.games = this.games.filter((g) => {
      if (g.id == id) g.selected = false;

      return true;
    });
    this.getSelected();
  }

  //Clear term types by user
  clearFilter() {
    this.searchText = '';
  }
}

Run Application

Now execute ng start to see the application in action

Conclusion

We have implemented the filter list feature on the dynamically created data list from the JSON object. The custom pipes in Angular can be created for various custom functionalities on the list items.

Leave a Reply

Your email address will not be published. Required fields are marked *