Debouncing Your Angular Search Field | Task

Ole Ersoy
Feb - 14  -  1 min

Scenario

We want to limit event notifications from our search field to a minimum of one event every 150 milliseconds.

Approach

imports

import { Component, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import {fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, tap } from 'rxjs/operators';

Declarations

Declare the input field:

@ViewChild('input') input: ElementRef;

Markup

<input placeholder="Search" #input>

Implementation

Note that we are using filter(Boolean) to make sure that we don’t pass undefined values:

ngAfterViewInit() {
    // server-side search
    fromEvent(this.input.nativeElement,'keyup')
          .pipe(
              filter(Boolean),
              debounceTime(150),
              distinctUntilChanged(),
              tap((text) => {
                console.log(this.input.nativeElement.value)
              })
          )
          .subscribe();
}

Demo