Create Observable from Event using FromEvent in Angular

Angular provides FromEvent method to create an observable from DOM events directly. In this article let us learn how to do that by creating an observable from the button click event, keyup even & scroll events.

Syntax

FromEventTarget is the first argument to fromevent. It can be a DOM EventTarget, Node.js EventEmitter, JQuery-like event target, NodeList or HTMLCollection. The target must have a method to register/unregister the event handler. (addEventListener/ removeEventListener in case of DOM Event target)

eventName is the second argument, which is a type of event we want to listen to.

Options are the additional argument that we want to pass to , when registering the event handler i.e addEventListener

resultSelector is optional and will be deprecated in future versions.

Example of fromEvent

To create an observable from any event, first, we need to get the reference to DOM element using the viewchild & ElementRef. For example the following code gets the reference to the button element with the id #btn

The code this.button.nativeElement returns the native DOM element. We pass this as the first argument to the fromEvent to create an observable to the click event.

We can invoke the above method from the ngAfterViewInit method. Note that the @ViewChildwill not initialize the btn element until the ngOnInit Hence we are using the ngAfterViewInit here.

How it works

When we subscribe to an observable, which we created using the fromEvent method, it registers the event handler using the addEventListener in the DOM element. Whenever the user clicks on the button, fromevent captures the value and emits it to the subscriber as the first argument. When we unsubscribe, it unregisters the event handler using the removeEventListener.

fromevent from button click

The following is the complete code of fromevent from a button click.

fromevent from scroll

The following code shows how to create observable from the window scroll event

fromevent from keyup

The following code shows how to create observable from a keyUp event.

Reference

  1. RxJs FromEvent API

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top