Create Observable From Event Using FromEvent In Angular

Create Observable From Event Using FromEvent In Angular

The FromEvent function in Angular allows you to construct an observable straight from DOM events. In this article, we will learn how to achieve it by building an observable from the button click, keyup, and scroll events.

Syntax

fromEvent<t>(target: FromEventTarget<t>, 
             eventName: string, 
             options: EventListenerOptions, 
             resultSelector: (...args: any[]) => T): Observable<t>

The first argument to fromevent is fromEventTarget. A DOM EventTarget, a Node.js EventEmitter, a JQuery-like event target, a NodeList, or an HTMLCollection can all be used. The event handler must be able to be registered and unregistered from the target. (in the case of DOM Event targets, addEventListener/removeEventListener)

The second option is eventName, which is the type of event we want to listen to.

Options are the extra arguments we wish to send to when registering an event handler, such as addEventListener.

resultSelector is a deprecated option that will be removed in future editions.

Example of fromEvent

To generate an observable from any event, we must first obtain a DOM element reference using viewchild & ElementRef. The following code, for example, obtains a reference to the button element with the id #btn.

In app.component.html,

<button btn="">Button</button>

In app.component.ts,

@ViewChild('btn', { static: true }) button: ElementRef;

this.button is the code. The native DOM element is returned by nativeElement. To construct an observable for the click event, we send this as the first input to the fromEvent.

buttonClick() {
  this.buttonSubscription =  fromEvent(this.button.nativeElement, 'click')
      .subscribe(res => console.log(res));
}

The ngAfterViewInit function can be used to call the above procedure. The @ViewChild will not initialize the btn element until the ngOnInit event occurs. As a result, we're using ngAfterViewInit in this case.

ngAfterViewInit() {
  this.buttonClick();
}

How it works

When we subscribe to an observable produced using the fromEvent method, the event handler is registered in the DOM element using the addEventListener method. When the user hits the button, fromevent takes the value and sends it as the first parameter to the subscriber. When we unsubscribe, the event handler is unregistered using the removeEventListener method.

fromevent from button click

The whole code for fromevent from a button click is shown below.

import { Component, Input, ViewChild, ElementRef, AfterViewInit, OnInit, OnDestroy } from '@angular/core';
import { Observable, of, from, fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit , OnInit, OnDestroy {
 
  title = 'Angular fromEvent Example';
 
  @ViewChild('btn', { static: true }) button: ElementRef;
  
  buttonSubscription
 
  constructor(private elm: ElementRef) {
  }
 
  ngOnInit() {
  }
 
 
  ngAfterViewInit() {
    this.buttonClick();
  }
 
 
  buttonClick() {
    this.buttonSubscription =  fromEvent(this.button.nativeElement, 'click')
        .pipe(debounceTime(300))
        .subscribe(res => console.log(res));
  }
 
 
  ngOnDestroy() {
    this.buttonSubscription.unsubscribe()
  }
 
}

fromevent from scroll

The code below demonstrates how to construct an observable from a window scroll event.

scroll() {
  const source = fromEvent(window, 'scroll');
  source.subscribe(val => console.log(val));
}

fromevent from keyup

The code below demonstrates how to make an observable from a keyUp event.

//Component
 
@ViewChild('name', { static: true }) name: ElementRef;
 
ngAfterViewInit() {
	fromEvent(this.name.nativeElement, 'keyup')
	.subscribe(res => console.log(res));
}

Conclusion

In this article, we learned how to achieve FromEvent by building an observable from the button click, keyup, and scroll events.

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.

Post a Comment

Previous Post Next Post