Angular +17 pipeline for filtering arrays
npm install ngx-mgmg-filter-pipe
{{ collection | filterBy: searchTerm }}
`
$3
| Param | Type | Details |
| --- | --- | --- |
| collection | array | The collection to filter |
| searchTerm | string or number or object or array or function | Predicate used to filter items from collection |
Install
`
npm install ngx-mgmg-filter-pipe
`
Usage
Import FilterPipe to your Standalone component or Module
`ts
@Component({
selector: 'app-root',
standalone: true,
imports: [
FilterPipe
],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
`
And use pipe in the template
`ts
import { Component } from '@angular/core';
@Component({
selector: 'example-app',
standalone: true,
imports: [FilterPip],
template:
})
export class AppComponent {
users: any[] = [{ name: 'John' }, { name: 'Jane' }, { name: 'Mario' }];
userFilter: any = { name: '' };
}
`
$3
Use $or to filter by more then one values.
$or expects an Array.
In your component:
`ts
// your array
const languages = ['English', 'German', 'Russian', 'Italian', 'Ukrainian'];
// your $or filter
const filter = { $or: ['German', 'English'] };
`
In your template:
`html
{{ language }}
`
Result will be:
`html
English
German
`
#### $or example with nessted values
In your component:
`ts
// your array
const languages = [
{ language: 'English' },
{ language: 'German' },
{ language: 'Italian' }
];
// your $or filter
const filter = {
language: {
$or: ['Italian', 'English']
}
};
`
In your template:
`html
{{ object.language }}
`
Result:
`html
English
Italian
`
#### $or example with multiple predicates
`
const objects = [
{ name: 'John' },
{ firstName: 'John' }
]
const filter = { $or: [{ name: 'John' }, { firstName: 'John' }] }
`
In your template:
`html
{{ object | json }}
`
Result:
`html
{ name: 'John' }
{ firstName: 'John' }
`
$3
Inject FilterPipe into your component and use it:
`ts
class AppComponent {
objects = [
{ name: 'John' },
{ name: 'Nick' },
{ name: 'Jane' }
];
constructor(private filter: FilterPipe) {
let result = this.filter.transform(this.objects, { name: 'J' });
console.log(result); // [{ name: 'John' }, { name: 'Jane' }]
}
}
``