Last active
April 14, 2020 05:44
-
-
Save shilpasyal55/cc7888c3b78596bbbbacb74bb3bf2591 to your computer and use it in GitHub Desktop.
Autocomplete component Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit ,ViewChild, ElementRef, Output, EventEmitter } from '@angular/core'; | |
import { of, fromEvent,Observable } from "rxjs"; | |
import { debounceTime, map,distinctUntilChanged,switchMap,tap } from "rxjs/operators"; | |
@Component({ | |
selector: 'app-autocomplete', | |
templateUrl: './autocomplete.component.html', | |
styleUrls: ['./autocomplete.component.css'] | |
}) | |
export class AutocompleteComponent implements OnInit { | |
@ViewChild('carSearchInput') carInput: ElementRef; | |
cars: any = []; | |
showSearches: boolean = false; | |
isSearching:boolean = false; | |
searchedCars: any = []; | |
constructor() { | |
this.cars = ['Audi', 'BMW', 'Bugatti', 'Ferrari', 'Ford', 'Lamborghini', 'Mercedes Benz', 'Porsche', 'Rolls-Royce', 'Volkswagen']; | |
} | |
ngOnInit() { | |
this.carSearch(); | |
} | |
carSearch() { | |
// Adding keyup Event Listerner on input field | |
const search$ = fromEvent(this.carInput.nativeElement, 'keyup').pipe( | |
map((event: any) => event.target.value), | |
debounceTime(500), | |
distinctUntilChanged(), | |
tap(()=> this.isSearching = true), | |
switchMap((term) => term ? this.getCars(term) : of<any>(this.cars)), | |
tap(() => { | |
this.isSearching = false, | |
this.showSearches = true; | |
})); | |
search$.subscribe(data => { | |
this.isSearching = false | |
this.searchedCars = data; | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment