该问题是因为Angular在渲染依赖选择下拉列表时没有正确地刷新初始数据列表。
一种解决方法是使用ngModel指令并绑定到父选择框中。我们可以通过监视ngModel的变化来更新子选择框。
在模板中,我们需要设置父选择框并绑定ngModel,同时给子选择框设置ngModel并绑定到一个函数,以便在子选择框的选项更改时更新数据。
下面是一个示例代码:
//HTML:
//Typescript: export class MyComponent { countries = [ { id: 1, name: 'USA' }, { id: 2, name: 'Canada' } ];
states = [ { id: 1, countryId: 1, name: 'California' }, { id: 2, countryId: 1, name: 'New York' }, { id: 3, countryId: 2, name: 'Ontario' }, { id: 4, countryId: 2, name: 'Quebec' } ];
selectedCountry: any; selectedState: any;
onCountryChange() { this.selectedState = null; this.states = this.states.filter(state => state.countryId === this.selectedCountry.id); } }