44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
|
import {Component, EventEmitter, Input, Output} from '@angular/core';
|
||
|
import {Location} from '@angular/common';
|
||
|
import {ActivatedRoute} from '@angular/router';
|
||
|
|
||
|
@Component({
|
||
|
selector: 'cc-list-search',
|
||
|
templateUrl: './search-field.component.html',
|
||
|
styleUrls: ['./search-field.component.css']
|
||
|
})
|
||
|
export class SearchFieldComponent {
|
||
|
|
||
|
@Input() searchTerm;
|
||
|
|
||
|
@Output() executeSearch = new EventEmitter();
|
||
|
|
||
|
@Output() searchTermStream = new EventEmitter();
|
||
|
|
||
|
constructor(private route:ActivatedRoute,
|
||
|
private location: Location) {
|
||
|
}
|
||
|
|
||
|
ngOnInit() {
|
||
|
const paramsObservable = this.route.queryParams
|
||
|
.map(params => decodeURI(params['query'] || ''))
|
||
|
.do(query => this.searchTerm.setValue(query));
|
||
|
|
||
|
const searchTermObservable = this.searchTerm.valueChanges
|
||
|
.debounceTime(400)
|
||
|
.do(query => this.adjustBrowserUrl(query));
|
||
|
this.searchTermStream.emit({params: paramsObservable, searchTerm: searchTermObservable});
|
||
|
}
|
||
|
|
||
|
emitSearch() {
|
||
|
this.executeSearch.emit();
|
||
|
}
|
||
|
|
||
|
adjustBrowserUrl(queryString = '') {
|
||
|
const absoluteUrl = this.location.path().split('?')[0];
|
||
|
const queryPart = queryString !== '' ? `query=${queryString}` : '';
|
||
|
|
||
|
this.location.replaceState(absoluteUrl, queryPart);
|
||
|
}
|
||
|
}
|