首頁 > web前端 > js教程 > 主體

如何在 Angular 中實現去抖動?

Barbara Streisand
發布: 2024-10-23 12:35:30
原創
975 人瀏覽過

How to Implement Debouncing in Angular?

Angular 中的去抖動

問題:

問題:

問題:

Angular 中如何實現去抖動?
<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>
登入後複製

答案:

在 Angular 2 中,可以在表單控制項值變更時使用 RxJS 運算子來實現去抖動。例如:

此程式碼以 1000 毫秒的延遲對擊鍵事件進行反跳。
<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>
登入後複製

最佳化技術:雖然上述方法是有效,它會觸發不必要的更改檢測。為了提高效率,請考慮在 Angular 的變更偵測區域之外建立 RxJS Observables 並手動呼叫 ChangeDetectorRef.detectChanges()。 這種方法可以防止不必要的更改檢測,從而提高效能。

以上是如何在 Angular 中實現去抖動?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!