Debouncing Your Angular Search Field

Ole Ersoy
1 min readAug 12, 2019
Photo by Aung Soe Min on Unsplash

Updated Version

There’s an updated version of this article here:

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:

Demo

Click on console to see the event and input being logged at most once every 150 milliseconds.

Bonus

To make sure that the the search function does not get called at when the field is empty add a filter(Boolean) to the pipe (This is the same as filter(v=>!!v):


pipe(
filter(Boolean),
debounceTime(150)

If you don’t want to debounce then just do this:

<input (keyup)="functionToCallOnKeyUp()">

Brought to You By

--

--