Home  >  Article  >  Web Front-end  >  How to Implement Debouncing in Angular?

How to Implement Debouncing in Angular?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 12:35:30976browse

How to Implement Debouncing in Angular?

Debouncing in Angular

Question:

How can debounce be implemented in Angular?

Answer:

In Angular 2 , debouncing can be achieved using RxJS operators on form control value changes. For example:

<code class="typescript">import {Component}   from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable}  from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';

@Component({
  selector: 'my-app',
  template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
    <br>{{firstName}}`
})
export class AppComponent {
  firstName        = 'Name';
  firstNameControl = new FormControl();
  ngOnInit() {
    this.firstNameControl.valueChanges
      .debounceTime(1000)
      .subscribe(newValue => this.firstName = newValue);
  }
}</code>

This code debounces keystroke events with a delay of 1000 milliseconds.

Optimization Techniques:

While the above approach is valid, it can trigger change detection unnecessarily. For efficiency, consider creating RxJS Observables outside of Angular's change detection zone and manually calling ChangeDetectorRef.detectChanges().

<code class="typescript">import {Component, NgZone, ChangeDetectorRef, ApplicationRef, 
        ViewChild, ElementRef} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';

@Component({
  selector: 'my-app',
  template: `<input #input type=text [value]="firstName">
    <br>{{firstName}}`
})
export class AppComponent {
  ngAfterViewInit() {
    Observable.fromEvent(this.inputElRef.nativeElement, 'keyup')
      .debounceTime(1000)
      .subscribe(keyboardEvent => {
        this.firstName = keyboardEvent.target.value;
        this.cdref.detectChanges();
      });
  }
}</code>

This approach prevents unnecessary change detection, improving performance.

The above is the detailed content of How to Implement Debouncing in Angular?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn