The filter operator helps you pick only the data you want from a stream of values. It works like a sieve, letting through only items that match your rule.
0
0
filter operator for selection in Angular
Introduction
When you want to react only to certain user actions, like clicks on a specific button.
When you receive many events but need to process only those with a certain property.
When working with data streams and you want to ignore unwanted values.
When you want to simplify your code by handling only relevant data.
When you want to avoid extra work by skipping unnecessary events.
Syntax
Angular
import { filter } from 'rxjs/operators'; observable.pipe( filter(value => condition) ).subscribe(filteredValue => { // handle filteredValue });
The filter operator is used inside the pipe() method of an observable.
The function inside filter returns true to keep the value, or false to skip it.
Examples
This example filters even numbers from a list and prints them.
Angular
import { of } from 'rxjs'; import { filter } from 'rxjs/operators'; of(1, 2, 3, 4, 5).pipe( filter(x => x % 2 === 0) ).subscribe(console.log);
This listens for clicks but only reacts if the click is on the right side of the screen.
Angular
import { fromEvent } from 'rxjs'; import { filter } from 'rxjs/operators'; const clicks = fromEvent(document, 'click'); clicks.pipe( filter((event: MouseEvent) => event.clientX > 200) ).subscribe(() => console.log('Clicked on right side'));
Sample Program
This Angular component listens for all clicks but updates the message only when Button 2 is clicked.
Angular
import { Component } from '@angular/core'; import { fromEvent } from 'rxjs'; import { filter } from 'rxjs/operators'; @Component({ selector: 'app-click-filter', template: ` <button id="btn1">Button 1</button> <button id="btn2">Button 2</button> <p>{{message}}</p> ` }) export class ClickFilterComponent { message = 'Click a button'; constructor() { const clicks = fromEvent(document, 'click'); clicks.pipe( filter((event: MouseEvent) => { const target = event.target as HTMLElement; return target.id === 'btn2'; }) ).subscribe(() => { this.message = 'Button 2 clicked!'; }); } }
OutputSuccess
Important Notes
Remember to import filter from rxjs/operators.
The filter function should be fast and simple to avoid slowing down your app.
Use TypeScript type assertions to help with event target types.
Summary
The filter operator lets you select only the values you want from a stream.
Use it inside pipe() with a function that returns true or false.
This helps keep your app efficient and focused on relevant data.