I have an ngFor that is iterating over an array of objects. I display this information in my table on the UI and it all works fine.
I am trying to implement a little filter box so I can narrow down the results based on what is entered into the box.
I am using a pipe for this and had it working with an array of data but I am not sure how to search through objects without specifying a specific key. I want to be able to enter search term and if it is a value in any one of the objects, filter it.
Pipe:
@Pipe({ name: 'filter' })
export class FilterPipe implements PipeTransform {
public transform(values: any[], filter: string): any[] {
if (!values || !values.length) return [];
if (!filter) return values;
return values.filter(v => v.indexOf(filter) >= 0);
}
}
Component:
dataObj = [
{
name: 'Bob',
age: 21,
location: 'USA'
},
{
name: 'Sally',
age: 25,
location: 'UK'
}]
filterString = '';
HTML:
<div>
<h2>Hello {{name}}</h2>
<input [(ngModel)]="filterString" />
<div *ngFor="let d of (dataObj | filter: filterString)">
{{ d.name }} - {{ d.age }} - {{ d.location }}
</div>
</div>
Desired Outcome:
If I entered 21 or Sally or US, I would expect to see results. I was trying to avoid hard coding a key into my pipe that it searches on as I wanted all values within the object to be searchable.
Here is a plnkr example: https://plnkr.co/edit/ubLyB152hgrPJSVp8xSB?p=preview