Skip to content

Instantly share code, notes, and snippets.

@jrodl3r
Last active November 2, 2019 20:41
Show Gist options
  • Save jrodl3r/5f5438516b57729154d4f279f8603a7a to your computer and use it in GitHub Desktop.
Save jrodl3r/5f5438516b57729154d4f279f8603a7a to your computer and use it in GitHub Desktop.
ElasticSearch - Angular Search Component
import { Component, OnDestroy, ViewChild, ElementRef } from '@angular/core';
import { Subscription, Subject, of } from 'rxjs';
import { debounceTime, delay, distinctUntilChanged, flatMap, map, tap } from 'rxjs/operators';
import { SearchService } from '../../services/search.service';
@Component({
selector: 'app-searchbox',
templateUrl: './searchbox.component.html',
styleUrls: ['./searchbox.component.scss']
})
export class SearchboxComponent implements OnDestroy {
@ViewChild('searchInput', { static: false }) searchInput: ElementRef;
inputSub: Subscription;
query: string;
resultsVisible = false;
updateSearch = new Subject<KeyboardEvent>();
constructor(public search: SearchService) {
this.search.reset();
this.inputSub = this.updateSearch.pipe(
map(event => (event.target as HTMLInputElement).value),
tap(query => {
if (!query) {
this.clearResults();
}
}),
debounceTime(250),
distinctUntilChanged(),
flatMap(query => of(query).pipe(delay(250)))
).subscribe(query => {
if (query.length && query !== this.query) {
this.query = query;
this.search.getResults(query);
this.showResults();
}
});
}
ngOnDestroy() {
this.inputSub.unsubscribe();
}
showResults() {
this.resultsVisible = true;
}
clearResults() {
this.resultsVisible = false;
this.search.reset();
this.query = '';
this.searchInput.nativeElement.value = '';
}
highlightResults(value: string) {
const location = value.toLowerCase().indexOf(this.query.toLowerCase());
return location >= 0
? value = value.substring(0, location)
+ '<span class="blue-text"><strong>'
+ value.substring(location, location + this.query.length)
+ '</strong></span>' + value.substring(location + this.query.length)
: value;
}
focusInput() {
this.searchInput.nativeElement.focus();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment