The Filter Operator in Angular filters the items emitted by the source Observable by using a condition (predicate). It emits only those values, which satisfies the condition and ignores the rest.
Table of Contents
Filter in Angular
Filter is the simplest and most used RxJs Operator in Angular. The Filter Operator takes 2 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 which satisfies the the predicate. The predicate
function takes 2 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 | 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 { ngOnInit() { of(1,2,3,4,5,6,7,8,9,10) .pipe( filter(val => { return val %2==0; }), ) .subscribe(val => console.log(val)); } } ***Console*** 2 4 6 8 10 |
Filter Empty or undefined
1 2 3 | filter(value => value !== undefined && value !== null) |
Filter object or array
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 { filter } from "rxjs/operators"; import { interval, of, timer } from "rxjs"; import { fromArray } from "rxjs/internal/observable/fromArray"; @Component({ selector: "my-app", template: ` <h1>Filter Example</h1> `, styleUrls: ["./app.component.css"] }) export class AppComponent { values = [ { name: "John", age: 30 }, { name: "alex", age: 40 } ]; ngOnInit() { fromArray(this.values) .pipe( filter(val => { return val.age > 30; }) ) .subscribe(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.