首页 > web前端 > js教程 > 正文

如何在 Angular 中实现去抖动?

Barbara Streisand
发布: 2024-10-23 12:35:30
原创
975 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!