角度2:反跳(ngModelChange)? [英] Angular 2: Debounce (ngModelChange)?
问题描述
是否可以消除模板指令(ngModelChange)
的反跳?
Is there a way to debounce the template directive (ngModelChange)
?
或者,用另一种方式来做这件事的痛苦最小的方法是什么?
Or, alternatively, what is the least-painful way to do it a different way?
我看到的最接近的答案是:如何观看Angular 2中的表单更改?
The closest answer I see is this: How to watch for form changes in Angular 2?
例如,我有一个文本输入,我想获取onChange更新,但是我想从每次击键中删除它:
So, for example, I have a text input, I want to get onChange updates, but I want to debounce it down from every keystroke:
<input type="text" class="form-control" placeholder="Enter a value" name="foo" [(ngModel)]="input.event.value" (ngModelChange)="onFieldChange($event, input)">
去抖动onFieldChange()
推荐答案
如果您不想使用formcontrol
方法,这是减轻键击痛苦的方法.
Here's the less painful way of debouncing keystrokes if you don't want to use the formcontrol
approach.
search.component.html
search.component.html
<input type="text" placeholder="Enter a value" name="foo" [(ngModel)]="txtQuery" (ngModelChange)="onFieldChange($event)">
search.component.ts
search.component.ts
export class SearchComponent {
txtQuery: string; // bind this to input with ngModel
txtQueryChanged: Subject<string> = new Subject<string>();
constructor() {
this.txtQueryChanged
.debounceTime(1000) // wait 1 sec after the last event before emitting last event
.distinctUntilChanged() // only emit if value is different from previous value
.subscribe(model => {
this.txtQuery = model;
// Call your function which calls API or do anything you would like do after a lag of 1 sec
this.getDataFromAPI(this.txtQuery);
});
}
onFieldChange(query:string){
this.txtQueryChanged.next(query);
}
}
这篇关于角度2:反跳(ngModelChange)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!