I am facing an issue with my <select>
elements in Angular. One for the Districts and another for the Cities. The districts are fetched using the getDistricts()
function within the ngOnInit()
function without any problems.
However, I am unsure how to dynamically update the cities based on the selected district. I attempted the following code snippet but encountered an error:
ORIGINAL EXCEPTION: TypeError: Cannot read property 'cities' of undefined
The error occurs because the initial value of selectedDistrict
is undefined.
Below is an example object representing a district, which includes its associated cities:
{
"id": 5,
"name": "A district",
"cities": [
{
"id": 59,
"name": "City 1"
},
{
"id": 60,
"name": "City 2"
}
]
},
district.service.ts:
import {Injectable} from "@angular/core";
import 'rxjs/add/operator/toPromise';
import {District} from "./district";
import {HttpClientService} from "../http-client/http-client.service";
@Injectable()
export class DistrictService {
private districtsUrl = 'districts/all';
constructor(private httpClient: HttpClientService) {
this.httpClient = httpClient;
}
getDistricts(): Promise<District[]> {
return this.httpClient.get(this.districtsUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
getDistrict(district: string): Promise<District> {
return this.getDistricts()[district];
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
view-search.component.ts:
export class ViewSearchComponent implements OnInit {
districts: district[];
selectedDistrict: district;
constructor(private districtService: districtService) {}
ngOnInit() {
this.getDistricts();
}
getDistricts() {
return this.districtService.getDistricts().then(districts => this.districts = districts);
}
selectDistrict(district: district) {
this.selectedDistrict = district;
}
}
view.search.component.html
<select class="search-select">
<option *ngFor="let district of districts" (click)="selectDistrict(district)">
{{ district.name }}
</option>
</select>
<select class="search-select">
<option *ngFor="let city of selectedDistrict.cities ">
{{ city.name }}
</option>
</select>