Rxjs Reactive Search Component in Angular 11 App

P SIVA KRISHNA REDDY
2 min readFeb 12, 2021

Hi Devs, This Article primarily focusses on creating a reactive search component with a demo youtube videos search angular app attached in the end. Rxjs library is available for other frameworks and programming languages as well.

Let’s first take a look at search component. Note: Rxjs 6+

Required Imports:

import { Component, ElementRef, EventEmitter, OnInit, Output } from '@angular/core';import { fromEvent } from 'rxjs';import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators';
  • fromEvent: it basically creates a Observable for Dom event of a DOM element which can be accessed via localRefs in angular;
  • pipe: The pipe() function takes one or more operators and returns an RxJS Observable. It is applied on any observable interface. all the following methods are used inside pipe.
  • debounceTime: Emits a value from the source Observable only after a particular time span has passed before another source emission on event changes.
  • distinctUntilChanged: Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from the previous item.
  • map: This operator is used to transform the observable data before outputting.
  • filter: Filter operator is similar to the map, except it filters out the data before the observable is subscribed to retrieve final output. it only emits a value from the source if it passes a criterion function.
Code for Reactive Search App.

Let’s Understand the Code Now.

Step 1: Register a DOM event using FromEvent method of rxjs. fromEvent(this.el.nativeElement, ‘keyup’)

el: ElementRef is injected in constructor which has a localReference for component which has only input field in our case. We can create a local reference for any DOM element and bind the event similarly.

Step 2: using pipe to do all the necessary transformations and checks. as explained earlier map, filter , debounceTime, distinctUntilChanged etc are used before the actual Observable output.

Step 3: pass the the final observable value to any api to fetch data based on input from user with 250 milliseconds delay.

Thus on every keystroke with a delay , a event is triggered on the search component by creating a observable stream and feeding it to any API call or service to Update the Data.

Check Out my Demo Application of a Youtube Data Api Search.

application Preview

Feel Free to Check Skulljackr’s Youtube as Well.

Hope You Liked this read, this is my first article, ignore any mistakes. Feel free to share the article if you like it.

#Angular #reactiveprogramming #framework #rxjs #youtube

--

--