added autocomplete

This commit is contained in:
Jonas Winkler
2020-10-27 17:05:14 +01:00
parent 2f549bec55
commit f978703105
5 changed files with 44 additions and 9 deletions

View File

@@ -6,7 +6,7 @@
</button>
<form (ngSubmit)="search()" class="w-100">
<input class="form-control form-control-dark" type="text" placeholder="Search" aria-label="Search"
[formControl]="searchField">
[formControl]="searchField" [ngbTypeahead]="searchAutoComplete" (selectItem)="itemSelected($event)">
</form>
<ul class="navbar-nav px-3">
<li class="nav-item text-nowrap">

View File

@@ -1,11 +1,13 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { from, Observable, of, scheduled, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, switchMap } from 'rxjs/operators';
import { PaperlessDocument } from 'src/app/data/paperless-document';
import { AuthService } from 'src/app/services/auth.service';
import { OpenDocumentsService } from 'src/app/services/open-documents.service';
import { SearchService } from 'src/app/services/rest/search.service';
@Component({
selector: 'app-app-frame',
templateUrl: './app-frame.component.html',
@@ -13,7 +15,7 @@ import { OpenDocumentsService } from 'src/app/services/open-documents.service';
})
export class AppFrameComponent implements OnInit, OnDestroy {
constructor (public router: Router, private openDocumentsService: OpenDocumentsService, private authService: AuthService) {
constructor (public router: Router, private openDocumentsService: OpenDocumentsService, private authService: AuthService, private searchService: SearchService) {
}
searchField = new FormControl('')
@@ -22,6 +24,35 @@ export class AppFrameComponent implements OnInit, OnDestroy {
openDocumentsSubscription: Subscription
searchAutoComplete = (text$: Observable<string>) =>
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
map(term => {
if (term.lastIndexOf(' ') != -1) {
return term.substring(term.lastIndexOf(' ') + 1)
} else {
return term
}
}),
switchMap(term =>
term.length < 2 ? from([[]]) : this.searchService.autocomplete(term)
)
)
itemSelected(event) {
event.preventDefault()
let currentSearch: string = this.searchField.value
let lastSpaceIndex = currentSearch.lastIndexOf(' ')
if (lastSpaceIndex != -1) {
currentSearch = currentSearch.substring(0, lastSpaceIndex + 1)
currentSearch += event.item + " "
} else {
currentSearch = event.item + " "
}
this.searchField.patchValue(currentSearch)
}
search() {
this.router.navigate(['search'], {queryParams: {query: this.searchField.value}})
}