I want to get a value from an input text after a few time (many millisecond or seconds) in angular 2, when a custom write an input but without waiting him to click a button.
I have tried this, but even when I use debounceTime
, value is send in every keypress.
I try to learn about debounce and observable and this is what I understand, Can anyone please help me to fix my code:
component.html:
<md-card-title *ngIf="!edit">{{card.title}}</md-card-title>
<input *ngIf="edit" type="text" [(ngModel)]="card.title" (ngModelChange)='rename()'/>
component.ts
newTitle: string;
modelChanged: Subject < string > = new Subject < string > ();
constructor()
this.modelChanged
.debounceTime(500) //before emitting last event
.distinctUntilChanged()
.subscribe(model => this.newTitle = model);
}
rename(): void {
this.renameRequest.emit(this.newTitle);
}
In JavaScript, a debounce function makes sure that your code is only triggered once per user input. Search box suggestions, text-field auto-saves, and eliminating double-button clicks are all use cases for debounce.
The value is a timeoutID that gets returned when we call setTimeout . This will allow us to reference the timeout created by calling setTimeout so that we can reset it each time our debounce function is used. The second action performed is calling setTimeout .
Debouncing is the delay of a function/method execution or an action for a period of the specified time. During this specified time, calls to the method/function or action are collected and executes each one when the specified has elapsed.
The major difference between debouncing and throttling is that debounce calls a function when a user hasn't carried out an event in a specific amount of time, while throttle calls a function at intervals of a specified amount of time while the user is carrying out an event.
Well, there is lot's of ways to achieve that, but here is one way :
<input *ngIf="edit" type="text" #input="ngModel" [(ngModel)]="card.title" (ngModelChange)='rename()'/>
And inside your class
newTitle : string;
@ViewChild('input') input;
constructor()
}
ngAfterViewInit(){
this.input.valueChanges
.pipe(debounceTime(500)) before emitting last event
.pipe(distinctUntilChanged())
.subscribe(model => (value)=>{
console.log('delayed key press value',value);
this.rename(value)
});
}
rename(value): void {
this.renameRequest.emit(value);
}
Here is the Plunker
You can even subscribe to modelChange like bellow :
ngAfterViewInit(){
this.input.update // this is (modelChange)
.pipe(debounceTime(500)) before emitting last event
.pipe(distinctUntilChanged())
.subscribe(model => (value)=>{
console.log('delayed key press value',value);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With