![](/img/trans.png)
[英]How to bind mat-autocomplete on change of other mat-autocomplete?
[英]How to update mat-autocomplete options from another component?
我的應用程序中有兩個名為 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;
});
}
此時,當我想清除 select a state 的城市列表並由所選 state 的城市填充時。 那么,我應該在哪里管理呢? 在 EmployeeComponent 上還是在 FormComponent 上? 而且我應該用一個優雅的解決方案設置城市列表選項嗎?
首先,您使用 2 mat-autocomplete。 這意味着相同的功能和行為。 在這種情況下,我更喜歡為該部分使用可重用的組件。
父組件中的 html
@Component({
selector: 'app-custom',
template: "<div *ngFor='let a of data'>{{a}}</div>",
})
export class CustomComponent {
@Input() data: string[] = [];
}
父組件中的 html
<div>
<h1>City</h1>
<app-custom [data]="city"></app-custom>
</div>
<div>
<h1>State</h1>
<app-custom [data]="state"></app-custom>
</div>
父組件中的 ts
export class AppComponent {
city: string[] = ['A', 'B', 'C'];
state: string[] = ['AAA', 'BBB', 'CSS'];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.