Categories
Angular Answers

How to add debounce with Angular?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *