How do you implement a search bar to filter a table?

1.3k Views Asked by At

I have a table of applications, with two columns - appAcronym and appName. There are around 250 rows of applications. I'd like to implement a search on top of the table/on the header to filter by appAcronym so user can access the desired row fast.

This is what the data looks like:

export interface App {
appId: number;
appName: string;
appAcronym: string;
}

This is my applications table

<table class="table table-striped table-hover table-sm" *ngIf="appsList">
        <thead>
            <tr>
                <th scope="col">Acronym</th>
                <th scope="col">System Name</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let app of appsList">
                <td>{{ app.appAcronym }}</td>
                <td>{{ app.appName }}</td>
            </tr>
        </tbody>
    </table>

This is my try at implementing a pipe

import { Pipe, PipeTransform } from '@angular/core';
import { App } from './components/applevel/applevel.component';
@Pipe({ name: 'searchByAcronym' })

export class SearchByAcronymPipe implements PipeTransform {
transform(appslist: App[], searchText: string, appAcronym: string) {

}

I am not familiar with pipes, and as you can see I've left the inside of the transform empty. Is a pipe the best tool for this job? If so can you suggest how to get this to work? The ideal implementation would be to have search on the Acronym header of the table. But an outside search bar works too.

2

There are 2 best solutions below

1
almcaffee On

You can clone this repo for an example of sorting and filtering with bootstrap column headers. https://github.com/almcaffee/angular-example1

You don't need pipes, pipes are for formatting data. You need some filtering or you could make an api call each time with the sort/filter parameters. The above example uses a static data set to perform as a backend service. Clone it to a folder, npm i, run it on localhost see how it behaves, go through the code, see what it's doing.

0
jfk On

I have recently implemented a filter for a table. Here is my solution

Pipe

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


@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(values: any, filterString: string): any {
    if (values.length === 0 || !filterString || filterString.length === 0) {
      return values;
    }
    const resultArray: App[] = [];
    for (const app of values) {
      if ((app.appName && app.appName.includes(filterString))
        || (app.appAcronym && 
            app.appAcronym.includes(filterString))
        
      ) {
        resultArray.push(app);
      }
    }
    return resultArray;
  }

}

Usage

 <input placeholder="Search here" [(ngModel)]="textSearch"></input>

<tr *ngFor="let app of appsList" | async | filter:textSearch >
                <td>{{ app.appAcronym }}</td>
                <td>{{ app.appName }}</td>
            </tr>