Home > Web Front-end > JS Tutorial > body text

How to Implement Debouncing in Angular?

Barbara Streisand
Release: 2024-10-23 12:35:30
Original
975 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!