如何从另一个组件更新 mat-autocomplete 选项?

How to update mat-autocomplete options from another component?

我的应用程序中有两个组件,名为 Employee 和 Form。 EmployeeComponent 中有 2 个 mat-autocomplete:State 和 City 列表。我使用“formData”参数填充这些 mat-autocomplete 控件并将其传递给 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 一个州时,我希望城市列表被清除并由 selected 州的城市填充。那么,我应该在哪里管理呢?在 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'];
}

Code