Angular 9|8 + Typescript: Create Filter List with Check-boxes to Select from List

Compatible with Angular versions 2,4,5,6,7,8 & 9 Hi Guys, here we will create a list of items with a filter using Angular and Typescript. For filtering list data we will use Pipes. Features: Filter from the list using the input search form field. Use the checkbox to select a game from the populated list. Selected…

By.

•

min read

Compatible with Angular versions 2,4,5,6,7,8 & 9

Hi Guys, here we will create a list of items with a filter using Angular and Typescript. For filtering list data we will use Pipes.

Features:

  1. Filter from the list using the input search form field.
  2. Use the checkbox to select a game from the populated list.
  3. Selected game tags will be added below the list items.
  4. A clear cross icon on search input to clear the search terms.
  5. “Clear Selection” to clear all selections by the user.
  6. An individual tag can be deleted using the cross icon on respective tags.

The complete version will look something like this:

You can try the demo here.

Step 1 – Create a filter “pipe” to Filter List

Create a file “filter.pipe.ts” with having below code:

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 2 - Include filter in main.ts file

Import filter.pipe.ts in main.ts file.

//main entry point
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { FormsModule } from '@angular/forms';
import { FilterPipe } from './filter.pipe';
import { AppModule } from './app';

platformBrowserDynamic().bootstrapModule(AppModule)

 

Step 3 - Let's create an app.ts file, which will have important logical functions explained in the feature section above.

//our root app component
import { Component, NgModule, VERSION } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser';
import { Pipe, PipeTransform } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FilterPipe } from './filter.pipe';

@Component({
  selector: 'my-app',
  template: `
    <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>
  `,
})
export class App {
  name: string;
  searchText: string = "";
  selected_count: number = 0;


  // 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
    }
  ]

  // 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 = "";
  }

  constructor() {
    this.name = `Angular! v${VERSION.full}`;
    this.getSelected();
  }
}

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [App, FilterPipe],
  bootstrap: [App]
})
export class AppModule { }

In the above code, every function is commented and self-explanatory. Let me know if you have any questions regarding code flow.

Find Source code in GitHub

UPDATE: See upgraded version on this example in Angular, having data sharing between components and routes example, usage of services and @Input decorator.

7 responses to “Angular 9|8 + Typescript: Create Filter List with Check-boxes to Select from List”

  1. Raymond Parwez Avatar
    Raymond Parwez

    •

    Hi,
    If I want to filter using an apply button how would I do that? I want to select a few radio buttons and once I click on the apply filter button it should filter it. Any help would be appreciated.
    Thanks
    Ray

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Please check this tutorial where we are filtering the data list when user clicks on the Filter button https://www.freakyjolly.com/dynamic-data-list-filtering-on-click-in-angular/ hope this helps
      Thanks, Jolly

  2. vikas Avatar
    vikas

    •

    it.name is undefined this error come in filter.pipe.ts file.

  3. Alejandro Almanza Avatar
    Alejandro Almanza

    •

    This was a lot of help for me. Thanks!!

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Glad to know 😛

  4. Kamlesh Katpara Avatar
    Kamlesh Katpara

    •

    Hi,

    How can I use / pass ‘selected_games’ to a different component ?

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Kamlesh, please check this post an upgrade of this . It will show how to pass data between components and Routes in Angular 6

Leave a Reply

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