Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  193] [ 1]  / answers: 1 / hits: 35141  / 8 Years ago, fri, december 23, 2016, 12:00:00

Is there a way to debounce the template directive (ngModelChange)?



Or, alternatively, what is the least-painful way to do it a different way?



The closest answer I see is this: How to watch for form changes in Angular 2?



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


Debounce onFieldChange()


More From » angular

 Answers
82

EDIT


In new version of Angular you can use updateOn in ngModelOption to set 'blur' for example. Link to angular.io documentation.


Code example :


<input [(ngModel)]="value"
[ngModelOptions]="{ updateOn: 'blur' }"
(ngModelChange)="updateOnlyOnBlur($event)">

LEGACY


Here's the less painful way of debouncing keystrokes if you don't want to use the formcontrol approach.



search.component.html



<input type="text" placeholder="Enter a value" name="foo" [(ngModel)]="txtQuery" (ngModelChange)="onFieldChange($event)">


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);
}
}

[#59580] Thursday, December 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janjadonb

Total Points: 4
Total Questions: 114
Total Answers: 118

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
janjadonb questions
;