Skip to content

Instantly share code, notes, and snippets.

@mirmilad
Created January 3, 2021 22:28
Show Gist options
  • Save mirmilad/665ca9f78d5be7ff618ccd2023a4dd69 to your computer and use it in GitHub Desktop.
Save mirmilad/665ca9f78d5be7ff618ccd2023a4dd69 to your computer and use it in GitHub Desktop.
a simple pipe for Angular that allows you filter array in template
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'dynamicFilter'
})
export class DynamicFilterPipe implements PipeTransform {
transform(items: any[], filter: any): any[] {
if (!items || !filter) {
return items;
}
const type = typeof filter;
if (type === 'function') {
return items.filter(filter);
} else {
return items.filter(item => this.compare(item, filter));
}
}
// This function compares all properties of filter object with item object to check if item is matched with filter object or not.
compare(item, filter) {
for (const prop in filter) {
if (filter[prop] !== item[prop]) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment