Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 911
Sunil Meena Avatar asked Dec 12 '18 11:12

Sunil Meena


Video Answer


1 Answers

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

like image 75
Akshay Rajput Avatar answered Sep 24 '22 15:09

Akshay Rajput