Created
January 3, 2021 22:28
-
-
Save mirmilad/665ca9f78d5be7ff618ccd2023a4dd69 to your computer and use it in GitHub Desktop.
a simple pipe for Angular that allows you filter array in template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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