Created
May 24, 2022 13:26
-
-
Save AngelAlexQC/838999de2dc42bf0971f07ae6293799a to your computer and use it in GitHub Desktop.
Angular Filter pipe
This file contains 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, Injectable } from '@angular/core'; | |
@Pipe({ | |
name: 'filter' | |
}) | |
@Injectable() | |
export class FilterPipe implements PipeTransform { | |
transform(items: any, filter: any, defaultFilter: boolean = true): any { | |
if (!filter) { | |
return items; | |
} | |
if (!Array.isArray(items)) { | |
return items; | |
} | |
if (filter && Array.isArray(items)) { | |
const filterKeys = Object.keys(filter); | |
if (defaultFilter) { | |
return items.filter(item => | |
filterKeys.reduce((x, keyName) => | |
(x && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] === '', true)); | |
} else { | |
return items.filter(item => { | |
return filterKeys.some((keyName) => { | |
return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === ''; | |
}); | |
}); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment