angular - 下拉列表中未填充的州和城市
问题描述
我是 Angular 的新手,在国家和城市的动态下拉列表中遇到了问题。尽管我已经在 StackOverflow 中检查了很多答案,但我无法清楚地了解我们应该如何成功编码以获得所需的结果。
countries: {};
states: {};
cities: {};
ngOnInit() {
this.getCountry()
}
<div class="form-group">
<select formControlName="country" class="form-control" (change)="onChangeCountry($event.target.value)">
<option value="">Select country...</option>
<option *ngFor="let country of countries" [value]="country.id">{{country?.name}}</option>
</select>
</div>
<div class="form-group">
<select formControlName="state" class="form-control"
(change)="onChangeState($event.target.value)">
<option value="">Select state...</option>
<option *ngFor="let state of states" [value]="state.id">{{state?.name}}</option>
</select>
</div>
<div class="form-group">
<select formControlName="city" class="form-control">
<option value="">Select city...</option>
<option *ngFor="let city of cities" [value]="city.id">{{city?.name}}</option>
</select>
</div>
getCountry(){
this._country.getCountries().subscribe((res: any) =>{
this.countries = res.data;
});
}
onChangeCountry(countryId: number) {
if (countryId) {
this._country.getStates(countryId).subscribe(
data => {
console.log(data)
this.states = data;
this.cities = null;
}
);
} else {
this.states = null;
this.cities = null;
}
}
onChangeState(stateId: number) {
if (stateId) {
this._country.getCities(stateId).subscribe(
data =>
this.cities = data
);
} else {
this.cities = null;
}
}
解决方案
你可以试试这个变量的初始化,
countries: any[] = [];
states: any[] = [];
cities: any[] = [];
将 any 替换为每个变量的类型。
推荐阅读
- php - 解析 HTML 文本,然后循环选择选项的文本和值
- c++ - 与类内初始化聚合 - 作为默认参数
- python-3.x - 有没有办法在不调用方法的情况下访问方法变量?
- expo - 如何解决来自monorepo中共享包博览会项目的导入
- wordpress - 无法使用 Terraform 在 azure 中创建 wordpress Web 应用程序
- amazon-web-services - 在其他组织上创建 Amazon S3 存储桶
- android - Cordova 相机在 iOS 上保存到图库后更改文件名
- r - 如何将列值转换为特定范围的 0 和 1
- applescript - 苹果脚本。将脚本的结果保存在 var 中
- python-3.x - 将文本文件中的文本拆分为行