将数据绑定到Angular中的层叠下拉列表/自动完成列表的正确方法是什么? [英] What is the proper way for binding data to cascade dropdown / autocomplete lists in 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
部分有关,因此,在尝试了许多不同的尝试以解决问题后,我感到非常困惑.因此,首先,我需要从一种适合级联绑定的适当方法开始.如何应用正确的方法?
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?
推荐答案
简而言之,丹尼尔(Daniel)的想法,您可以定义一个可观察的对象,例如
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">
Usig 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
)
}
请注意,此想法返回了一个可观察的结果,并在.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屋!