Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call keyup event with delay in angular

I have text box and assigned to it keyup event a search function but I want it to happen with delay, not on every keypress

here is the html code :

<input type="text" [(ngModel)]="searchedKPI" (keyup)="searchConfigTree()">

and here is ts code :

list = list.filter(item => item.label.toLocaleLowerCase().includes(this.searchedKPI.toLocaleLowerCase())).slice();

and here is the example I wanted to search "text" string but the event happens 4 times, I want to this happens once only for "text" string :

enter image description here

what the solution?

like image 721
Vala Khosravi Avatar asked Oct 03 '17 05:10

Vala Khosravi


3 Answers

Welcome to the Observable's world. Just use Observable to get the desired result. Get the reference of your input in the component and use this code. debounceTime will let the event to trigger at least after 1 second from the previous trigger. It will let you not to fire on every keyup when user types fast.

Observable.fromEvent(yourInput, 'keyup').debounceTime(1000).subscribe(value => /* */)

In the subscribe method you can write your logic. The value is the value of the input.

like image 108
Suren Srapyan Avatar answered Nov 13 '22 22:11

Suren Srapyan


View template.html

<input type="text" [(ngModel)]="searchedKPI" (keyup)="searchConfigTree()" #something>

component.ts (do not forget implement the AfterViewInit)

     source: any;
     @ViewChild("something") something:ElementRef; 

     ngAfterViewInit(): void {
                this.source = fromEvent(this.something.nativeElement, 'keyup');
                this.source.pipe(debounceTime(1200)).subscribe(c => 
                {
                          list = list.filter(item => item.label.toLocaleLowerCase().includes(this.searchedKPI.toLocaleLowerCase())).slice();
                }
                );
              }
like image 29
Esteban Perez Avatar answered Nov 13 '22 23:11

Esteban Perez


This solution works for me

View Template.html

<input type="text" placeholder="Filter..." class="form-control" [(ngModel)]="filter" (input)="searchChange($event.target.value, true)">
<button class="btn btn-primary" type="button" (click)="searchChange(filter, false)"><i class="fa fa-search"></i></button>

Comonent.ts

  filter= '';
  private timer: any;

  searchChange(filter: string, to = false) {
    filter = filter.toLowerCase();

    if (to) {
      clearTimeout(this.timer);

      this.timer = setTimeout(() => {
        this.valuesFilter = this.allValues.filter(f => f.field.toLowerCase().includes(filter));
      }, 400);
    } else {
      this.valuesFilter = this.allValues.filter(f => f.field.toLowerCase().includes(filter));
    }
  }
like image 1
Stivens Avatar answered Nov 13 '22 23:11

Stivens