import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { LocationService } from '../../services/location.service'; import { phoneNumberValidator } from '../../utils/sync-validators'; import { phoneNumberMask, zipCodeMask } from '../../utils/input-masks'; @Component({ selector: 'md-address-form', templateUrl: './address-form.component.html' }) export class AddressFormComponent implements OnInit { constructor(private formBuilder: FormBuilder, private locationService: LocationService) {} @Input('title') title: string; @Output() formReady = new EventEmitter(); addressForm: FormGroup; phoneNumberMask = phoneNumberMask; zipCodeMask = zipCodeMask; states = []; cities = []; loadedCity = ''; ngOnInit(): void { this.addressForm = this.formBuilder.group({ zipCode: [null, [Validators.required, Validators.pattern(/\d{5}\-\d{3}/)]], streetAddress: [null, Validators.required], number: [null, Validators.required], complement: [null], district: [null, Validators.required], state: [null, Validators.required], city: [null, Validators.required], phoneNumber: [null, [phoneNumberValidator.bind(this)]] }); this.addressForm .get('state') .valueChanges.subscribe(selectedStateCode => this.loadCities(selectedStateCode)); this.addressForm.get('zipCode').valueChanges.subscribe((zipCode: string) => { const cleanPostalCode = zipCode.replace(/\D/g, ''); this.loadAddress(cleanPostalCode); }); this.formReady.emit(this.addressForm); this.loadStates(); } loadAddress(zioCode: string): void { if (zioCode.length === 18) { this.locationService.getAddress(zioCode).subscribe(response => { if (!response.logradouro) { return; } this.addressForm.get('streetAddress').setValue(response.logradouro.toUpperCase()); this.addressForm.get('district').setValue(response.bairro.toUpperCase()); const state: any = this.states.find((s: any) => s.initials === response.uf); this.loadedCity = response.localidade; this.addressForm.get('state').setValue(state.code); }); } } loadStates(): void { this.locationService.getStates().subscribe(response => { this.states = response.map(state => ({ ...state, description: state.description.toUpperCase() })); }); } loadCities(stateCode: string): void { this.locationService.getCities(stateCode).subscribe(response => { this.cities = response; if (this.loadedCity) { const city = this.cities.find(c => c.description === this.loadedCity.toUpperCase()); this.addressForm.get('city').setValue(city.description); } }); } }