首页  >  文章  >  web前端  >  如何在 Angular 中实现去抖动?

如何在 Angular 中实现去抖动?

Barbara Streisand
Barbara Streisand原创
2024-10-23 12:35:30976浏览

How to Implement Debouncing in Angular?

Angular 中的去抖动

问题:

Angular 中如何实现去抖动?

答案:

在 Angular 2 中,可以在表单控件值更改时使用 RxJS 运算符来实现去抖。例如:

<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>

此代码以 1000 毫秒的延迟对击键事件进行反跳。

优化技术:

虽然上述方法是有效,它会触发不必要的更改检测。为了提高效率,请考虑在 Angular 的更改检测区域之外创建 RxJS Observables 并手动调用 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>

这种方法可以防止不必要的更改检测,从而提高性能。

以上是如何在 Angular 中实现去抖动?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn