0

我的应用程序中有两个名为 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 上?而且我应该用一个优雅的解决方案设置城市列表选项吗?

4

1 回答 1

1

首先,您使用 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'];
}

代码

于 2020-12-14T00:07:53.247 回答