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 中實現去抖動?的詳細內容。更多資訊請關注PHP中文網其他相關文章!