首页 > 解决方案 > 下拉列表中未填充的州和城市

问题描述

我是 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;
  }
}

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

标签: angular

解决方案


你可以试试这个变量的初始化,

countries: any[] = [];
states: any[] = [];
cities: any[] = [];

将 any 替换为每个变量的类型。


推荐阅读