Sunil Meena
Sunil Meena

Reputation: 541

Delay in input change Angular

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

Upvotes: 24

Views: 32017

Answers (3)

Malte Bruweleit
Malte Bruweleit

Reputation: 1

Just came across this issue and tried to find an improved solution. Came up with the following using the ReactiveForms capabilities and RxJs (debounceTime).

Bind the input with the formControl attribute.

<input [formControl]="control">

Put it together in the typescript component.

control = new FormControl();

constructor() {
  this.control.valueChanges
    .pipe(debounceTime(500))
    .subscribe((value: string) => {
      // do something with the value
    });
}

Upvotes: 0

Arun Kumar
Arun Kumar

Reputation: 209

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

Upvotes: 9

Akshay Rajput
Akshay Rajput

Reputation: 2078

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

Upvotes: 36

Related Questions