Angular 2: Debounce (ngModelChange)?

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

Or, alternatively, what is the least painful way to do it differently?

The closest answer I see is the following: How to view form changes in Angular 2?

So, for example, I have text input, I want to get updates for the update, but I want to drop it from every keystroke:

 <input type="text" class="form-control" placeholder="Enter a value" name="foo" [(ngModel)]="input.event.value" (ngModelChange)="onFieldChange($event, input)"> 

onFieldChange() failure

+8
javascript angular
source share
2 answers

Here's a less painful way to debounceing 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); } } 
+12
source share

If you want to add debounceTime when making an http call, you can use Subject , which is very easy to use. This is also explained in the angular2 tutorial - HTTP .

+4
source share

All Articles