https://acme-company.github.io/ng-filter/
npm install ng-filter --save
import { NgModule } from "@angular/core";
...
import { AppModule as FilterModule } from 'ng-filter';
@NgModule({
imports: [
...
FilterModule
],
...
})
export class AppModule {
}
<div>
Filter <input [(ngModel)]="name" />
</div>
<table class="table table-hover">
<thead>
<tr>
<td sort="firstName">First Name</td>
<td sort="lastName">Last Name</td>
<td sort="birthDate">Birthdate</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of people | filter: name">
<td>{{ person.firstName }}</td>
<td>{{ person.lastName }}</td>
<td>{{ person.birthDate | date:'yyyy-MM-dd' }}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">
</td>
</tr>
</tfoot>
</table>
Add the FilterService to the providers array of your list component. The scope of FilterService should not be global because it tracks filter callbacks for a single list.
import { Component } from '@angular/core';
import { FilterService } from 'ng-filter';
export interface Person {
firstName: string;
lastName: string;
birthDate: Date;
}
@Component({
selector: 'app',
templateUrl: './app.component.html',
providers: [FilterService]
})
export class AppComponent {
name = '';
people: Person[] = [];
constructor(filterService:FilterService<Person>) {
filterService.configure({
firstName: (person:Person, value:string) => new RegExp('^' + value.trim(), 'i').test(person.firstName),
lastName: (person:Person, value:string) => new RegExp('^' + value.trim(), 'i').test(person.lastName),
birthDate: (person: Person, value: string) => new DatePipe('en-US').transform(person.birthDate,'yyyy-MM-dd').startsWith(value)
});
this.people = [
{ firstName: 'James', lastName: 'Dean', birthDate: new Date(2012, 5, 1) },
{ firstName: 'John', lastName: 'Smith', birthDate: new Date(2012, 5, 1) },
{ firstName: 'Jane', lastName: 'Doe', birthDate: new Date(2011, 1, 1) },
{ firstName: 'Terry', lastName: 'Rundle', birthDate: new Date(2015, 6, 12) },
{ firstName: 'Barry', lastName: 'White', birthDate: new Date(2009, 3, 19) },
];
}
}
The filterService
provides a configure
method which accepts a configuration object. Each property of the configuration object can be set to a custom filter predicate.
The filter predicate has the following signature (where T is the item type from the array of items being filtered):
function(item:T, value:string): boolean {
...
return true; // or false
}
If the predicate returns true, then the item will be included in the filtered list. Otherwise, the item will be excluded.
For example, if the item type is a string:
Filter <input [(ngModel)]="name" />
<div *ngFor="let item of list | filter: name">
{{ item }}
</div>
filterService.configure({
item: (item:string, value:string) => item.startsWith(value)
});
this.list = [
"apples",
"pears",
"bannas"
];