Efficient-angular
GitHubToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeBack to homepage

FromEvent

Creates an Observable that emits events of a specific type coming from the given event target.

Syntax

fromEvent<T>(target: any, eventName: string, options?: EventListenerOptions | ((...args: any[]) => T), 
resultSelector?: (...args: any[]) => T): Observable<T>
ParametersDescription
targetThe DOM EventTarget, Node.js EventEmitter, JQuery-like event target, NodeList or HTMLCollection to attach the event handler to.
eventNameThe event name of interest, being emitted by the target.
options optionalDefault is undefined. Options to pass through to addEventListener
resultSelector optionalDefault is undefined. Type: (...args: any[]) => T.

Returns

Observable<T>: 

An observable that emits events of a specific type coming from the given event target.

Examples

Emits clicks happening on the DOM document

import { fromEvent } from 'rxjs';

const clicks = fromEvent(document, 'click');
clicks.subscribe(x => console.log(x));

// Results in:
// MouseEvent object logged to console every time a click
// occurs on the document.

Use addEventListener with capture option

import { fromEvent } from 'rxjs';
 
const clicksInDocument = fromEvent(document, 'click', true); // note optional configuration parameter
                                                             // which will be passed to addEventListener
const clicksInDiv = fromEvent(someDivInDocument, 'click');
 
clicksInDocument.subscribe(() => console.log('document'));
clicksInDiv.subscribe(() => console.log('div'));
 
// By default events bubble UP in DOM tree, so normally
// when we would click on div in document
// "div" would be logged first and then "document".
// Since we specified optional `capture` option, document
// will catch event when it goes DOWN DOM tree, so console
// will log "document" and then "div".