[英]How to update mat-autocomplete options from another component?
I have two components called Employee and Form in my application.我的应用程序中有两个名为 Employee 和 Form 的组件。 There are 2 mat-autocomplete: State and City lists in EmployeeComponent.
EmployeeComponent 中有 2 个 mat-autocomplete:State 和 City 列表。 I fill and pass these mat-autocomplete controls to the FormComponent using "formData" parameter:
我使用“formData”参数填充这些垫子自动完成控件并将其传递给 FormComponent:
Employee Component:员工组件:
html html
<form #form [formData]="formControls"></app-form>
ts 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;
});
Form Component:表单组件:
html 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;
});
}
At this point, when I select a state I want the cities list is cleared and the filled by the cities of the selected state.此时,当我想清除 select a state 的城市列表并由所选 state 的城市填充时。 So, where should I manage this?
那么,我应该在哪里管理呢? On EmployeeComponent or on FormComponent?
在 EmployeeComponent 上还是在 FormComponent 上? And hoca should I set the cities list options with an elegant solution?
而且我应该用一个优雅的解决方案设置城市列表选项吗?
First of all, you use 2 mat-autocomplete.首先,您使用 2 mat-autocomplete。 That means the same functionality and behavior.
这意味着相同的功能和行为。 In this situation, I prefer to use a reusable component for that part.
在这种情况下,我更喜欢为该部分使用可重用的组件。
html in parent component父组件中的 html
@Component({
selector: 'app-custom',
template: "<div *ngFor='let a of data'>{{a}}</div>",
})
export class CustomComponent {
@Input() data: string[] = [];
}
html in parent component父组件中的 html
<div>
<h1>City</h1>
<app-custom [data]="city"></app-custom>
</div>
<div>
<h1>State</h1>
<app-custom [data]="state"></app-custom>
</div>
ts in parent component父组件中的 ts
export class AppComponent {
city: string[] = ['A', 'B', 'C'];
state: string[] = ['AAA', 'BBB', 'CSS'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.