将数据绑定到 Angular 中的级联下拉/自动完成列表的正确方法是什么? [英] What is the proper way for binding data to cascade dropdown / autocomplete lists in Angular?

查看:15
本文介绍了将数据绑定到 Angular 中的级联下拉/自动完成列表的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中的几个地方使用了 mat-autocomplete 并在表单加载时将它们填写如下:

I use mat-autocomplete in several places in my project and fille them as shwon below on form loading:

countries: CountryDto[] = [];
cities: CityDto[] = [];


getCountries() {
  this.demoService.getCountries().subscribe((list: CountryDto) => {
    this.countries = list;
  });
}

getCities(countryId) {
  this.demoService.getCities(countryId).subscribe((list: CityDto) => {
    this.cities= list;
  });
}

但是,当我尝试使用第二个列表作为级联时,我无法根据第一个选择来填充第二个列表.实际上我通过 countryId 然后检索城市列表没有任何问题.但是,我无法刷新城市列表.我也尝试使用 changeDetectorRef.detectChanges()ngZone.run(),但这没有任何意义.我不确定问题是否与 subscribe 部分有关,因此在尝试了许多不同的 tging 来解决问题后,我太困惑了.因此,首先我需要从适合级联绑定的正确方法开始.怎样才能应用得当?

However, when I tried to use a second list as cascade, I cannot make the second one to fill according to the first selection. Actually I pass the countryId and then retrieve the city list without any problem. But, I cannot refresh the list of cities. I also tried to use changeDetectorRef.detectChanges() and ngZone.run(), but it does not make any sense. I am not sure if the problem is related to subscribe section, and for this reason I am too confused after trying lots of different tgings to fix the problem. So, first I need to start with a proper approach that is suitable for cascade binding. How can apply a proper way?

推荐答案

简单化大牛的想法,你可以定义一个像 observable 一样的

Simplifly the Daniel's idea, you can defined a observable like

cities$=this.citiesForm.get('state').valueChange.pipe(
  switchMap(countryId=>this.demoService.getCities(countryId),
  tap(_=>this.citiesForm.get('city').setValue(null)
)

并使用

<options *ngFor="let s of cities$ | async">

使用 ngModel 是相等的

Usig ngModel is equal

<select [ngModel]="state" (ngModelChange)="stateChange($event)" >
 ...
</select>


stateChange(countryId)
{
  this.state=state;
  this.cities$=this.demoService.getCities(countryId).pipe(
      tap(_=>this.city=null
  )
}

看到这个想法是返回一个 observable 并在 .html 中使用管道异步.操作员轻敲"做到这一点,当您订阅时-记住管道异步是一种订阅方式-城市变为空

See that the idea is return an observable and use pipe async in the .html. The operator "tap" make that, when you subscribe -remember that the pipe async is a way to subscribe- the city becomes null

这篇关于将数据绑定到 Angular 中的级联下拉/自动完成列表的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆