I have a pipe filter, that filters the list of my clients by name
. I need to add another filter, so the clients could be filtered by account_number
The filter pipe:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'filter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(items: any[], term): any {
return term ? items.filter(item => item.name.toLowerCase().indexOf(term.toLowerCase()) != -1) : items;
}
}
In my view, I bind the filter in the way like this:
<input type="text" class="form-control" placeholder="Name" name="term" [(ngModel)]="term">
<input type="number" class="form-control" placeholder="Account number"> <!--Here I want to make another ngModel-->
<table>
<tr *ngFor="let client of clients | filter: term | sortBy: 'id'; let i = index"
<td>{{client.name}}</td>
<td>{{client.account_number}}</td>
</tr>
</table>
So, do I need to make another pipe
for filtering by a different property, or can it be done in a single pipe
? Also, if it will be two different pipes, how should I include it to the filter in the view? Thanks.
you can do it with single pipe try this
transform(values: any[], filter: string): any {
if (!values || !values.length) return [];
if (!filter) return values;
filter = filter.toUpperCase();
if (filter && Array.isArray(values)) {
const keys = Object.keys(values[0]);
return values.filter(v => v && keys.some(k => v[k].toUpperCase().indexOf(filter) >= 0));
}
}