How to add debounce with Angular?

Sometimes, we want to add debounce with Angular.

In this article, we’ll look at how to add debounce with Angular.

How to add debounce with Angular?

To add debounce with Angular, we can use the subject.

For instance, we write

<input [ngModel]="model" (ngModelChange)="changed($event)" />

to add an input in our template.

We call changed if the input value is changed.

Then in the component class, we write

import { Subject } from "rxjs/Subject";
import { Component } from "@angular/core";
import "rxjs/add/operator/debounceTime";

export class ViewComponent {
  model: string;
  modelChanged: Subject<string> = new Subject<string>();

  constructor() {
    this.modelChanged
      .debounceTime(300)
      .distinctUntilChanged()
      .subscribe((model) => (this.model = model));
  }

  changed(text: string) {
    this.modelChanged.next(text);
  }
}

to create the modelChanged subject.

In the constructor, we call debounceTime to add the debounce in milliseconds.

And then we call distinctUntilChanged to emit the value only if it’s difference from the previous one.

Then we call subscribe with a callback to listen for the emitted value and set the value of this.model to the emitted value.

Next, in changed, we call this.modelChanged.next with text to emit the latest input value.

Conclusion

To add debounce with Angular, we can use the subject.