Sunday, February 3, 2019

Get .debounceTime working with an autosuggestion feature in an Angular 6 application.

One of things this FormControl has going for it...

import {FormControl} from '@angular/forms';

 
 

...is that you may do a .valueChanges.debounceTime(500) off of a FormControl type variable, but then again... everyone hates the forms. What if you just want to make something simple like this...

<input id="iAmSpecial" />

 
 

...in the template of a component and have it serve as a search box for searching wherein there is an autocomplete feature that goes to the server based on what you type but which will wait until you are done typing for a half second so that it does not just go to the server every time you type a letter? Alright, let's make that happen. First of all, I thought this would have to do with doing a .debounceTime off of the Observable I got back from the server/API, but really we need to do a .debounceTime before we ever reach the code that tries to even call out to the server/API. This has an example and we will need these imports at our component.

import { Component, OnInit, HostListener, OnDestroy } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';

 
 

In our component we need two private variables like so:

private subject = new Subject();
private subscription: Subscription;

 
 

We also need two events in our component:

  1. ngOnInit(){
       this.subscription = this.subject.pipe(
          debounceTime(500)
       ).subscribe((e:any) => {
          alert(e.srcElement.value);
       });
    }

     
  2. ngOnDestroy() {
       this.subscription.unsubscribe();
    }

 
 

I know the any above is a bit hacky and also you won't want to have an alert right? Instead of the alert you will want to either call a different method that calls the server/API or I guess you could less elegantly just have the code you might have in that method where the alert is without any more abstraction. Lastly, we need a HostListener to make all of the magic work. An example:

@HostListener('keyup', ['$event'])
clickEvent($event) {
   if ($event && $event.target && $event.target.id == "iAmSpecial")
   {
      $event.preventDefault();
      $event.stopPropagation();
      this.subject.next($event);
   }
}

No comments:

Post a Comment