import { Component, Input } from '@angular/core'; import { TypeaheadSelectOption, TypeSafeFormGroup } from '@yourcause/common'; import { map, Observable } from 'rxjs'; import { LookupService } from '../../services/lookup.service'; import { LocationState } from '../../states/location.state'; import { SpecialHandlingFormGroup } from '../special-handling-modal/special-handling-modal.component'; export interface AddressFormGroup { name?: string; address1: string; address2: string; countryCode: string; city: string; stateProvRegCode: string; postalCode: string; } @Component({ selector: 'gc-address-block', templateUrl: './address-block.component.html', styleUrls: ['./address-block.component.scss'] }) export class AddressBlockComponent { @Input() addressFormGroup: TypeSafeFormGroup | TypeSafeFormGroup; @Input() countryDisabled = false; @Input() disableInputs = false; regionsExist: boolean; countrySelects$: Observable = this.locationState.changesTo$('countries').pipe( map(countries => (countries).map(country => ({ label: country.name, value: country.code })))); regionSelects$: Observable = this.locationState.changesTo$('regions').pipe( map((regionMap) => { const countries = this.locationState.countries; const countryCode = this.addressFormGroup.value.countryCode; if (countryCode) { const country = countries.find(({ code }) => code === countryCode); this.regionsExist = !!regionMap[countryCode] || !country?.hasState; if (!this.regionsExist) { this.lookupService.getStatesByCountryId(country.id) .then((result) => { this.locationState.set('regions', { ...regionMap, [countryCode]: result }); }); } return regionMap[countryCode] || []; } else { this.regionsExist = false; } return []; }), map(regions => regions.map(region => ({ label: region.name, value: region.code })))); constructor ( private locationState: LocationState, private lookupService: LookupService ) { } setRegionsOnCountryChange () { this.locationState.triggerChange('regions'); } }