Skip to content
Index

[RxJS] Convert DOM events to an Observable stream

Tested with: RxJS v7

To handle DOM element events in a declarative and functional reactive way, you can convert them to an Observable stream using the RxJS fromEvent creation function.

This way, you can use RxJS operators to manipulate the stream of events and combine it with other streams.

import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
const button = document.querySelector('button');
const buttonClick$ = fromEvent(button, 'click');
// Subscribe to the Observable stream, debouncing the clicks to prevent reacting to too many clicks at once.
const subscription = buttonClick$
.pipe(debounceTime(1000))
.subscribe(() => console.log('Button clicked!'));
// Make sure to to call `subscription.destroy()` to dispose properly of the subscription when done.
// For example, in an Angular component's `ngOnDestroy` lifecycle hook.

Now, when the button is clicked, the message “Button clicked!” will be logged to the console, but only after a 1 second debounce time (so multiple clicks within 1 second will be ignored).