I am trying to auto-populate the city based on zip code value. So far I have been able to match the user input zip code with a static list of zip code but I am facing trouble implementing the logic to fetch the cities corresponding to the zip code entered by the user.
Below is a snippet of the ts and html file from my app
test.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Validators } from '@angular/forms';
import { FormArray } from '@angular/forms';
@Component({
selector: 'test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
profileForm = this.fb.group({
organizationAddress: this.fb.group({
street:['', Validators.required],
zip: ['', Validators.required],
city: ['', Validators.required],
state:['', Validators.required]
})
});
zip = {
"city1": ["1", "2" ],
"city2":[ "3", "4", "5"],
"city3":[ "6", "7" ]
};
onKeyUp(event: any){
let city, zipCodes = this.zip, score;
for (let i=0; i<Object.keys(zipCodes).length; i ){
Object.values(zipCodes).forEach(function (value){
for( let zip in value){
if(event.target.value == `${value[zip]}`){
score = `${value[zip]}`;
break;
}
}
if(score = Object.values(zipCodes))
{
console.log("city ",Object.keys(score))
city = Object.keys(score);
}
})
}
this.profileForm.patchValue({
organizationAddress:{
city: city}
})
}
test.component.html
<div formGroupName="organizationAddress">
<h4>Address</h4>
<label for="zip">Zip Code : </label>
<input id="zip" type="text" formControlName="zip" (keyup)="onKeyUp($event)"><br/>
<label for="city">City : </label>
<input id="city" type="text" formControlName="city"><br/>
</div>
CodePudding user response:
Here's a simple function that returns the correct city for a given zip code:
zipCodes = {
"city1": ["1", "2" ],
"city2":[ "3", "4", "5"],
"city3":[ "6", "7" ]
};
getCity = theCurrentZip => {
return Object.keys(zipCodes).filter(z => {
return zipCodes[z].includes(theCurrentZip)
})[0]
}
console.log(getCity("7"))
console.log(getCity("2"))
console.log(getCity("99"))