我的应用程序中有两个名为 Employee 和 Form 的组件。EmployeeComponent 中有 2 个 mat-autocomplete:State 和 City 列表。我使用“formData”参数填充这些垫子自动完成控件并将其传递给 FormComponent:
员工组件:
html
<form #form [formData]="formControls"></app-form>
ts
formControls = [];
states: StateDto[] = [];
cities: CityDto[] = [];
// fill employee list
getStates() {
this.demoService.getStates().subscribe((data: StateDto) => {
this.states = data;
});
}
getCities() {
this.demoService.getCities().subscribe((data: CityDto) => {
this.cities = data;
});
}
// create for data array
this.formData = [
{
id: 'states',
type: 'custom-autocomplete',
},
{
id: 'cities',
type: 'custom-autocomplete',
}
]
// set form control's list data
this.formControls = this.formData.map(item => {
if (item.id === 'states') {
item.options = this.states;
}
else if (item.id === 'cities') {
item.options = this.cities;
}
return item;
});
表单组件:
html
@Input() formData = [];
options = {};
ngOnInit() {
//code omitted for brevity
this.autocompleteControl.forEach(item => {
// here I set each autocomplete's options
this.options[item.id] = item.options;
});
}
此时,当我选择一个州时,我希望清除城市列表并由所选州的城市填充。那么,我应该在哪里管理呢?在 EmployeeComponent 上还是在 FormComponent 上?而且我应该用一个优雅的解决方案设置城市列表选项吗?