When the page loads it gets the countries from my rest api and when a user choose a country it loads the cities for the country. It works fine so far but when the page is opened, the city is empty beacuse it only gets the citeies when the user at least once choose a country (the (change) event).
To avoid this i want to gets the first element of the countries[] and load the cities with the country id in ngInit.
But it always undefined if i want to get an elemnt from the countries array. I tried multiple ways but i can't get it to work.
Country Model:
export interface Country{
id: number;
name: string;
}
Component.ts:
countries: Country[] = [];
cities : City[] = [];
loading: boolean = false;
errorMessage: string | undefined;
constructor(
private countryService: CountryServiceService,
private cityService: CityService) {
}
ngOnInit(): void {
this.getCountries();
console.log(this.countries[0]);
}
getCountries()
public getCountries(){
this.countryService.getCountries().subscribe( response => {
this.countries = response;
}
)
}
HTML:
<select (change)="getCities($event)">
<option *ngFor="let country of countries"
[value]="country.id">
{{country.name}}
</option>
</select>
<select>
<option *ngFor="let city of cities"
[value]="city.id">
{{city.name}}
</select>
CodePudding user response:
There is many ways to do this. but in your way that you want. you can try below.
and I believe you have getCities(countryId:number)
method. so just do this.
public getCountries(){
this.countryService.getCountries().subscribe( response => {
this.countries = response;
this.fillCities(this.countries[0].id);
}
}
fillCities(id:number){
this.cityService.getCities(id).subscribe( response => {
this.cities=response;
}
}
you need to handle type checks/ validations. Above code is straight forward as per your requirement.