如何设置角度的动态级联下拉列表的值?

时间:2019-03-28 18:48:15

标签: angular angular6 angular-reactive-forms

我正在开发一个使用反应形式的Angular 6应用程序。在一个表单中,我有一个区域下拉列表,该列表基于另一个国家下拉列表中的选定值进行填充。问题是,在显示从数据库中获取的数据时设置国家/地区列表的值时,将触发其更改事件(这将加载选定国家/地区的区域)。在尝试设置已编辑记录的区域值之前,此更改事件尚未完成,因此,永远不会设置正确的区域值。

下面是我的代码:


constructor(
    public fb: FormBuilder,
    private dataservice: DataService
)
{
    this.form = this.fb.group({
        country: [null],
        region: [null]
    });
}

ngOnInit(): void {

this.form
      .get("country")!
      .valueChanges.pipe(debounceTime(200))
      .subscribe(countryName => {

            this.form.patchValue({
              region: null
            });

            this.loadRegions(countryName);
      });

this.loadCountriesList();

this.loadData();

}

private loadCountriesList() {
    this.countriesList = [];

    this.dataservice.getCountries().subscribe((countries) => {
        this.countriesList = countries;

        if (countries.length > 0) {
            this.form.controls["country"].setValue("US");
        }

    });
}

private loadRegions(countryName: string) {
    this.regions = [];

    this.dataservice
        .getRegions(countryName)
        .subscribe((regions) => {
            this.regions = regions;
        });
}

loadData(){
    this.dataservice.getRecord(5).subscribe(data => {
        this.form.patchValue({
            country: data.countryName;
            region: data.region; //Problem: the value of the region is not set here
        });
    });
}

不确定我是否做错了什么,或者是否有其他/更好的方法来做同样的事情。

1 个答案:

答案 0 :(得分:0)

我认为您必须将this.loadCountriesList()和this.loadData();直接在下面this.loadRegions(countryName);

ngOnInit(): void {

   this.form
  .get("country")!
  .valueChanges.pipe(debounceTime(200))
  .subscribe(countryName => {

        this.form.patchValue({
          region: null
        });

        this.loadRegions(countryName);
        this.loadCountriesList();
        this.loadData();
  });



 }