In some cases, System has to provide suggestions to user while user typing. Sending request for each and every request to server will be overhead. So sending request to server when user finishes typing will give good performance. We can detect whether user typing or finished his typing by delaying the change event.
Source Code             DEMO

Markup

displayName function will be triggered when user changes input
<input (ngModelChange)="displayName()" [(ngModel)]="name"/>

Script - app.component.ts

Observe below displayName function
import { Component } from '@angular/core';
import { NgZone } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
   <h4>Type something in below text box</h4>
   <input (ngModelChange)="displayName()" [(ngModel)]="name"/>
   <h4>Value : {{name1}} </h4>
  `
})
export class AppComponent {
   name: string = '';
   name1: string = '';
   _timeout: any = null;

   constructor(public lc: NgZone) {

   }

   displayName() {
     this._timeout  = null;
     if(this._timeout){ //if there is already a timeout in process cancel it
       window.clearTimeout(this._timeout);
     }
     this._timeout = window.setTimeout(() => {
        this._timeout = null;
        this.lc.run(() => this.name1 = this.name);
     },1000);
  }
}

2 comments:

  1. Nice work man, but I think you need to remove `this._timeout = null;` before your `if(this._timeout){` as it will always be null

    ReplyDelete
  2. Previous comment is right.

    Apart from that it works perfect, thanks for your solution!

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts