Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable, Inject, Component, OnInit, AfterViewInit, NgZone, ElementRef, NgModule, ViewChild } from '@angular/core';
- import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
- import { Http, HttpModule, Response, Headers, RequestOptions } from '@angular/http';
- import { trigger, state, animate, keyframes, transition, style } from '@angular/animations';
- import { Router, ActivatedRoute } from '@angular/router';
- import { MatAutocompleteSelectedEvent } from '@angular/material';
- import { AgmCoreModule, MapsAPILoader } from '@agm/core';
- import { } from '@types/googlemaps';
- import { SearchService } from '../../../services/search.service';
- import { ISearchTrade } from '../../../models/search.trade.interface';
- import { ICategory } from '../../../models/category.interface';
- import { TranslationEmitterService } from '../../../services/translation.emitter.service';
- import { fadeInAnimation } from '../../../animations/fadeIn.animation';
- import { slideInFadeInAnimation } from '../../../animations/slideInFadeIn.animation';
- import { Subscription } from 'rxjs/Rx';
- import { Observable } from 'rxjs/Observable';
- import { startWith } from 'rxjs/operators/startWith';
- import { map } from 'rxjs/operators/map';
- import 'rxjs/add/operator/catch';
- @Component({
- selector: 'searchTrade',
- templateUrl: './searchTrade.component.html',
- styleUrls: ['./searchTrade.component.css'],
- animations: [
- trigger(
- 'moveLabel', [
- state('moveUp', style({
- opacity: 0.75,
- top: '4px',
- fontSize: '14px'
- })),
- state('moveDown', style({
- opacity: 1.0,
- top: '20px',
- fontSize: '14px'
- })),
- transition('* => moveUp', animate('400ms ease-in-out')),
- transition('* => moveDown', animate('400ms ease-in-out'))
- ]),
- fadeInAnimation,
- slideInFadeInAnimation
- ],
- providers: [SearchService]
- })
- export class SearchTradeComponent {
- filteredOptions: Observable<ICategory[]>;
- options: ICategory[];
- categorySubscription: Subscription;
- translationSubscription: Subscription;
- private details: ISearchTrade = { trade: '', location: '' };
- searchForm: FormGroup;
- toHighlight: string = '';
- errors: string = '';
- isRequesting: boolean = false;
- submitted: boolean = false;
- state: string = 'moveDown';
- tradeState: string = 'moveDown';
- locationState: string = 'moveDown';
- formState: string = 'active'; //can ba active, submitting, complete, error
- public latitude: number;
- public longitude: number;
- public trade: number;
- @ViewChild("search")
- public searchElementRef: ElementRef;
- googlePlacesOptions = {
- types: [],
- componentRestrictions: { country: 'PT' }
- };
- constructor(
- fb: FormBuilder,
- private router: Router,
- private service: SearchService,
- private translationService: TranslationEmitterService,
- private http: Http,
- private mapsAPILoader: MapsAPILoader,
- private ngZone: NgZone) {
- this.searchForm = fb.group({
- 'tradeCtrl': ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.pattern('[^0-9]*')])],
- 'locationCtrl': ['', Validators.compose([Validators.required])]
- });
- }
- ngOnInit() {
- this.categorySubscription = this.service.getCategories().subscribe((categories: ICategory[]) => {
- this.options = categories;
- this.filteredOptions = this.searchForm.get('tradeCtrl').valueChanges
- .pipe(
- startWith(''),
- map(options => options ? this.filter(options) : this.options.slice())
- );
- });
- //load Places Autocomplete
- this.mapsAPILoader.load().then(() => {
- let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
- types: ["address"]
- });
- autocomplete.addListener("place_changed", () => {
- this.ngZone.run(() => {
- //get the place result
- let place: google.maps.places.PlaceResult = autocomplete.getPlace();
- //verify result
- if (place.geometry === undefined || place.geometry === null) {
- return;
- }
- //set latitude, longitude
- this.latitude = place.geometry.location.lat();
- this.longitude = place.geometry.location.lng();
- });
- });
- });
- this.translationSubscription = this.translationService.languageChange$.subscribe(
- lang => this.refreshAutoCompleteItems(lang)
- // x => console.log("translate subscription " + x)
- );
- }
- ngOnDestroy() {
- this.categorySubscription.unsubscribe();
- this.translationSubscription.unsubscribe();
- }
- refreshAutoCompleteItems(lang: string) {
- console.log("in subscription " + lang);
- }
- filter(val: string): ICategory[] {
- this.toHighlight = val;
- return this.options.filter(x =>
- x.name.toUpperCase().indexOf(val.toUpperCase()) !== -1
- );
- }
- onTradeSelected(event: any, selected: ICategory) {
- if (event.isUserInput) {
- this.trade = selected.id;
- }
- }
- inputFocusIn(event: any) {
- console.log("in input focus");
- switch (event.target.id) {
- case 'tradeCtrl':
- this.tradeState = 'moveUp';
- break;
- case 'locationCtrl':
- this.locationState = 'moveUp';
- break;
- }
- }
- inputFocusOut(event: any) {
- if (this.searchForm.get(event.target.id)!.value == null ||
- this.searchForm.get(event.target.id)!.value != "")
- return;
- switch (event.target.id) {
- case 'tradeCtrl':
- this.tradeState = 'moveDown';
- break;
- case 'locationCtrl':
- this.locationState = 'moveDown';
- break;
- }
- }
- submit(form: any): void {
- console.log("in the form submit");
- console.log(form);
- this.submitted = true;
- this.isRequesting = true;
- this.errors = '';
- if (this.searchForm.valid) {
- let headers = new Headers({ 'Content-Type': 'application/json' });
- let options = new RequestOptions({ headers: headers });
- this.details.trade = form['tradeCtrl'];
- this.details.location = form['locationCtrl'];
- this.formState = 'submitting';
- this.service.find(this.details.trade, this.details.location)
- .finally(() => this.isRequesting = false)
- .subscribe(
- result => {
- if (result) {
- this.router.navigate(['/dashboard/home']);
- }
- },
- error => this.errors = error);
- }
- else {
- Object.keys(this.searchForm.controls).forEach(key => {
- this.searchForm.controls[key].markAsTouched();
- this.searchForm.controls[key].markAsDirty();
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment