19

Hello I have an input in my application which fires on every stroke but I want some delay so for eg. trigger my search function after 1 sec so that it doesn't send multiple requests

My Html Code

<input id="musicsearch"
  (input)="onSearchChange($event.target.value)"  
  ng-model-options="{debounce:1000}" 
  class="form-control mr-sm-2"style="width: 100%;"
  type="text"placeholder="Search">

component.ts (which handles change)

 onSearchChange(searchValue : string ) {    
    this.router.navigate(['/search', searchValue]);      
  }

I am new to angular I can't find solution for my problem, I want to trigger this when user stop typing in input

AlignedDev
  • 8,102
  • 9
  • 56
  • 91
Sunil Meena
  • 481
  • 3
  • 10
  • 19

2 Answers2

31
  private modelChanged: Subject<string> = new Subject<string>();
  private subscription: Subscription;
  debounceTime = 500;

  ngOnInit(): void {
    this.subscription = this.modelChanged
      .pipe(
        debounceTime(this.debounceTime),
      )
      .subscribe(() => {
        this.functionToBeCalled();
      });
  }
  functionToBeCalled() {
    console.log('Called After 500ms');
  }

  inputChanged() {
    this.modelChanged.next("Akshay Is Awesome")
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

html file <input type="text" (keydown)="inputChanged()">

Try This Thanks me later :)

Akshay Rajput
  • 1,978
  • 1
  • 12
  • 22
  • @Akashay Cannot find name 'Subject'. , Cannot find name 'Subscription'. and Cannot find name 'debounceTime'. Did you mean the instance member 'this.debounceTime'? – Sunil Meena Dec 12 '18 at 12:39
  • @SunilMeena,You need to import those.. If you look at the link i provided in my answer comment you will come to know.. – Maniraj Murugan Dec 12 '18 at 12:41
  • 2
    import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; Hope This helps :) – Akshay Rajput Dec 12 '18 at 12:41
  • error in import => Module '"c:/xampp/htdocs/Angular/app/node_modules/rxjs/Subscription"' has no exported member 'Subscription'. – Sunil Meena Dec 12 '18 at 12:43
  • open your package.json and please let me know rxjs version – Akshay Rajput Dec 12 '18 at 12:47
  • 3
    I've found if you use the (keyup) event you'll get all characters. (keydown) was leaving off the last character for me. – Nate Apr 15 '21 at 21:39
  • 1
    Hi @Nate the event has been added just for reference purpose, we can use change, input, keydown or another valid event :) – Akshay Rajput Apr 16 '21 at 05:12
5

On Html file

<input [(ngModel)]="searchTxt" type="text" (keyup)="triggerSearch()">

On ts file

searchTxt:string = '';
timeout = null;

triggerSearch() {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => {
      this.onSearchChange(this.searchTxt);
    }, 1000);
  }
Arun Kumar
  • 135
  • 2
  • 4