Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

debounce angular 2 with ngModelChange

I have a ngModelChange on a textArea like this :

      <ion-textarea placeholder="Type your message here" formControlName="message" [(ngModel)]="message" (ngModelChange)="changing($event)"></ion-textarea>

And now I'd like to know where the user is typing on this textarea or not, so I'd like to use debounce with a timmer of 5000 for example to know if he's typing or not, not sending for every letter he's typing, I want to fire this event every 5 seconds, how could I implement it?

like image 369
StuartDTO Avatar asked Jul 13 '17 07:07

StuartDTO


2 Answers

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="text" (keyup)='keyUp.next($event)'>
    </div>
  `,
})
export class App {
  name:string;

  public keyUp = new Subject<string>();

  constructor() {
    const observable = this.keyUp
      .map(value => event.target.value)
      .debounceTime(1000)
      .distinctUntilChanged()
      .flatMap((search) => {
        return Observable.of(search).delay(500);
      })
      .subscribe((data) => {
        console.log(data);
      });
  }
}
like image 105
Rahul Singh Avatar answered Sep 30 '22 14:09

Rahul Singh


Create a Subject in your component. In your changing method call next on the subject. Next subscribe to your subject with a debounce:

export class MyComponent {
  mySubject = new Subject();

  contructor(){
    this.mySubject
      .debounceTime(5000)
      .subscribe(val => {
        //do what you want
      });
  }

  changing(event){
    this.mySubject.next(event.valueFromInput);
  }
}
like image 32
Robin Dijkhof Avatar answered Sep 30 '22 13:09

Robin Dijkhof