import {Component, OnInit, ViewChild} from '@angular/core'; import {FieldType} from '@ngx-formly/material'; import {debounceTime, distinctUntilChanged, filter, switchMap, tap} from 'rxjs/operators'; import {AllService} from '../../../all.service'; import {concat, Observable, of, Subject} from 'rxjs'; @Component({ selector: 'jhi-cutom-cp', templateUrl: './cutom-cp.component.html', styleUrls: ['./cutom-cp.component.scss'] }) export class CutomCpComponent extends FieldType implements OnInit { cities$: Observable; citiesLoading = false; citiesInput$ = new Subject(); minLengthTerm = 3; citySelected = null; model: any = {}; constructor(private allService: AllService) { super(); } ngOnInit() { this.tranformModelToValue(); this.loadCities(); } loadCities() { this.cities$ = concat( of([]), // default items this.citiesInput$.pipe( filter(res => { return res !== null && res.length >= this.minLengthTerm }), distinctUntilChanged(), debounceTime(800), tap(() => this.citiesLoading = true), switchMap(term => { return this.getCities(term); }) ) ); } async getCities(term: string = null): Promise { const responseCustomerVariable = await this.allService.referenceManagerService.search(term).toPromise(); this.citiesLoading = false; if (responseCustomerVariable.length > 0) { return responseCustomerVariable; } else { return []; } } setToModel(): void { if (this.citySelected) { this.model[this.field['variable']] = this.citySelected.zipCode + '|' + this.citySelected.city; this.formControl.setValue(this.model[this.field['variable']]); } else { this.model[this.field['variable']] = null; this.formControl.setValue(''); } this.field.templateOptions.change(this.field); } public tranformModelToValue(): void { let customCity = []; if (this.model[this.field['variable']]) { customCity = this.model[this.field['variable']].split('|'); this.citySelected = { zipCode: customCity[0], city: customCity[1], }; } else if (this.field.templateOptions['multipleVariable']) { let city = this.model[this.field.templateOptions['multipleVariable'].city]; let zipCode = this.model[this.field.templateOptions['multipleVariable'].zipCode]; if (city) { city = city.trim(); } if (zipCode) { zipCode = zipCode.trim(); } if (city && zipCode && this.model[this.field.key]) { this.citySelected = { zipCode, city }; } } } }