【发布时间】:2026-01-31 03:10:01
【问题描述】:
我有一个下拉列表(区域),它定义了下一个(城市)应该显示的内容
区域.ts
@Component({
selector: 'app-region-dropdown',
templateUrl: './region-dropdown.component.html',
styleUrls: ['./region-dropdown.component.css'],
providers: [RegionService, CityDropdownComponent]
})
export class RegionDropdownComponent implements OnInit {
regions: Array<Region>;
constructor(private regionsService: RegionService, private cityDropDown: CityDropdownComponent) { }
ngOnInit() {
this.regionsService.getAll().subscribe(data => {
this.regions = data;
});
}
public onChange(value):void {
console.log(value);
this.cityDropDown.loadList(value);
}
}
城市.ts
@Component({
selector: 'app-city-dropdown',
templateUrl: './city-dropdown.component.html',
styleUrls: ['./city-dropdown.component.css'],
providers: [RegionService]
})
export class CityDropdownComponent implements OnInit {
cities: Array<City>;
constructor(private regionsService: RegionService) { }
ngOnInit() {
}
public loadList(regionId: number) {
this.regionsService.getCities(regionId).subscribe(data => {
console.log(data);
this.cities = data;
});
}
}
city.html
<mat-form-field>
<mat-select placeholder="City">
<mat-option *ngFor="let city of cities" >
{{city.name}}
</mat-option>
</mat-select>
</mat-form-field>
控制台显示 regionService 返回了一个列表,但城市列表从未更新
【问题讨论】:
-
您确定返回的数据是针对城市而不是针对地区的吗?
-
提供者中的CityDropdownComponent?
-
@GregoryMazur 使用共享服务在 onChange() 函数中传递值。使用共享服务和主题。
-
先尝试将城市变量设置为一个空列表:city: Array
= []; (在声明中)可能是没有对象的时候不能有onChange()事件。 -
如果您在 StackBlitz 上遇到问题,我们可以尝试在那里解决。您的代码中没有明显的错误,但我看到有一些关于在 gihub 中动态更改 mat-select 可能会影响您的讨论。
标签: angular typescript angular7