如何在用户的值完全输入到输入中之前延迟Angular doCheck执行?

时间:2019-09-12 21:34:10

标签: html angular

我正在使用follow doCheck()方法来确定用户的输入在处理之前是否已更改。

ngDoCheck() {
    if (this.filter.price !== this.oldPrice) {
      // this.changeDetected = true;
      console.log(`DoCheck: Price changed to "${this.filter.price}" from 
        "${this.oldPrice}"`);
      this.oldPrice = this.filter.price
    }
  }

问题是用户输入的每个数字都会调用ngDoCheck。我更喜欢让用户先完成输入,然后再像在rxjs中使用debounceTime进行处理一样。

2 个答案:

答案 0 :(得分:1)

如果这是来自FormControl的用户输入,我建议您订阅valueChanges,可使用debounceTime运算符进行观察。但是,如果您坚持要使用,也可以使用ngDoCheck的每次调用将下一个值放入您自己的可观察对象中:

import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

class YourComponent {
  private changeSubject = new Subject();

  ngOnInit() {
    this.changeSubject.pipe(
      distinctUntilChanged(),
      debounceTime(400)
    ).subscribe( value => {
      console.log('debounced value:', value);
    });
  }

  ngDoCheck() {
    this.changeSubject.next(this.filter.price);
  }
}

答案 1 :(得分:0)

使用更改而不是生命周期挂钩

HTML:

<input (change)="change($event)">

组件:

  change(newValue) {
    console.log(newValue);
  }