I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.
Here is the Pipe being called in an *ngFor directive,
<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
Hello {{item.first}} !
</div>
Here is the Pipe,
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
transform(myobjects: Array<object>, args?: Array<object>): any {
if (args && Array.isArray(myobjects)) {
// copy all objects of original array into new array of objects
var returnobjects = myobjects;
// args are the compare oprators provided in the *ngFor directive
args.forEach(function (filterobj) {
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
// return new array of objects to *ngFor directive
return returnobjects;
}
}
}
And here is the Component containing the object to filter,
import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
items = [{ title: "mr", first: "john", last: "jones" }
,{ title: "mr", first: "adrian", last: "jacobs" }
,{ title: "mr", first: "lou", last: "jones" }
,{ title: "ms", first: "linda", last: "hamilton" }
];
}
GitHub Example: Fork a working copy of this example here
*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.
Happy Coding :-)