In AngularJS I can debounce a model by using ng-model options.
ng-model-options="{ debounce: 1000 }"
How can I debounce a model in Angular? I tried to search for debounce in the docs but I couldn't find anything.
https://angular.io/search/#stq=debounce&stp=1
A solution would be to write my own debounce function, for example:
import {Component, Template, bootstrap} from 'angular2/angular2';
// Annotation section
@Component({
selector: 'my-app'
})
@Template({
url: 'app.html'
})
// Component controller
class MyAppComponent {
constructor() {
this.firstName = 'Name';
}
changed($event, el){
console.log("changes", this.name, el.value);
this.name = el.value;
}
firstNameChanged($event, first){
if (this.timeoutId) window.clearTimeout(this.timeoutID);
this.timeoutID = window.setTimeout(() => {
this.firstName = first.value;
}, 250)
}
}
bootstrap(MyAppComponent);
And my html
<input type=text [value]="firstName" #first (keyup)="firstNameChanged($event, first)">
But I'm looking for a build in function, is there one in Angular?
If you don't want to deal with
@angular/forms
, you can just use an RxJSSubject
with change bindings.view.component.html
view.component.ts
This does trigger change detection. For a way that doesn't trigger change detection, check out Mark's answer.
Update
.pipe(debounceTime(300), distinctUntilChanged())
is needed for rxjs 6.Example:
Since the topic is old, most of the answers don't work on Angular 6.
So here is a short and simple solution for Angular 6 with RxJS.
Import necessary stuff first:
Initialize on
ngOnInit
:Use this way:
P.S.: For more complex and efficient solutions you might still want to check other answers.
Spent hours on this, hopefully I can save someone else some time. To me the following approach to using
debounce
on a control is more intuitive and easier to understand for me. It's built on the angular.io docs solution for autocomplete but with the ability for me to intercept the calls without having to depend on tying the data to the DOM.Plunker
A use case scenario for this might be checking a username after it's typed to see if someone has already taken it, then warning the user.
Note: don't forget,
(blur)="function(something.value)
might make more sense for you depending on your needs.It could be implemented as Directive
use it like
component sample
For Reactive Forms and handling under Angular v2(latest) plus v4 look at:
https://github.com/angular/angular/issues/6895#issuecomment-290892514
Hopefully there will be native support for these kinds of things soon...
Simple solution would be to create a directive which you can apply to any control.
usage would be