24

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

1
  • maybe use (blur) instead of (input)?
    – Rick
    Commented Jul 22, 2020 at 19:42

2 Answers 2

36
  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 :)

7
  • @Akashay Cannot find name 'Subject'. , Cannot find name 'Subscription'. and Cannot find name 'debounceTime'. Did you mean the instance member 'this.debounceTime'? Commented Dec 12, 2018 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.. Commented Dec 12, 2018 at 12:41
  • 2
    import { Subject } from 'rxjs/Subject'; import { Subscription } from 'rxjs/Subscription'; import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; Hope This helps :) Commented Dec 12, 2018 at 12:41
  • 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
    Commented Apr 15, 2021 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 :) Commented Apr 16, 2021 at 5:12
8

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);
  }

Not the answer you're looking for? Browse other questions tagged or ask your own question.