The Filter Operator in Angular filters the items emitted by the source Observable using a condition (predicate). It emits only those values that satisfy the condition and ignores the rest.
Table of Contents
Filter in Angular
The filter is the simplest and most used RxJs Operator in Angular. The Filter Operator takes two arguments.
Syntax
1 2 3 | filter<T>(predicate: (value: T, index: number) => boolean, thisArg?: any): MonoTypeOperatorFunction<T> |
The first argument is the predicate
 function. This function is evaluated against each value of the source observable. Filter emits only those values that satisfy the predicate. The predicate function takes two parameters. The first one is the value emitted by the source. The second argument is zero-based index
.Â
The second argument thisArg
is Optional. It determines the value of this
in the predicate
function
Filter Example
The following example filter function returns true only if the value is an even number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import { Component } from "@angular/core"; import { filter } from "rxjs/operators"; import { interval, of, timer } from "rxjs"; @Component({ selector: "my-app", template: ` <h1>Filter Example</h1> `, styleUrls: ["./app.component.css"] }) export class AppComponent implements OnInit { ngOnInit() { of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .pipe( filter((val) => { return val % 2 == 0; }) ) .subscribe({ next: (val) => console.log(val), }); } } ***Console*** 2 4 6 8 10 |
We use the new syntax (introduced in RxJs 6.4) for subscribing to observables’ angular. You can also use the older syntax, which is shown below.
1 2 3 | .subscribe(val => console.log(val)); |
Filter Empty or undefined
The following code will filter the empty or undefined values from the observable array.
1 2 3 | filter(value => value !== undefined && value !== null) |
Filter object or array
The code below uses the filter operator to filter the observable stream of objects. It will return only if the age exceeds 30 and discards the rest.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import { Component } from '@angular/core'; import { map, filter } from 'rxjs/operators'; import { from, of } from 'rxjs'; @Component({ selector: 'my-app', template: ` <h1>Filter Example</h1> `, }) export class AppComponent { values = [ { name: 'John', age: 30, }, { name: 'alex', age: 40, }, ]; ngOnInit() { from(this.values) .pipe( filter((val) => { return val.age > 30; }) ) .subscribe({ next:(val) => console.log(val) }); } } |
Reference
Read More
fromArray is only available in rxjs version 6 I believe. Please verify you version of ‘rxjs’ in package.json if you have issues importing.