Filter Operator In Angular
In this article, we will learn about the Filter Operator in Angular. The Filter Operator in Angular uses a condition to filter the items emitted by the source Observable (predicate). It only emits values that satisfy the requirement and ignores everything else.
Filter in Angular
In Angular, the Filter operator is the most basic and often used RxJs operator. The Filter Operator is a two-argument operator.
Syntax
filter<t>(predicate: (value: T, index: number) => boolean, thisArg?: any): MonoTypeOperatorFunction<t>
The predicate function is the first argument. Each value of the source observable is used to evaluate this function. Only values that satisfy the predicate are output by the filter. There are two parameters in the predicate function. The first is the value that the source emits. The zero-based index is the second argument.
Optional is the second parameter, thisArg. In the predicate function, it decides the value of this.
Filter Example
Only an even number returns true in the following sample filter function.
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
filter(value => value !== undefined && value !== null)
Filter object or array
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)); } }
Conclusion
In this article, we learned what is Filter Operator and how to use it in Angular.
I hope this article helps you and you will like it.👍
If you have any doubt or confusion then free to ask in the comment section.