angular 7 中的多个共享级联组合框组件

Multiple shared cascading combobox component in angular 7

我创建了一个组件来管理级联 国家和州。如果我只组建一个国家和一个州,一切都会完美无缺。但是,当我放置三个国家和州时,一切都会像下面的示例一样损坏。我怎样才能做到这一点?

一个国家(工作示例)

Stackblitz

三个国家(无效示例)

Stackblitz

您有两个元素引用了相同的变量:

<app-country [studentForm]="studentForm"></app-country>
<app-state [studentForm]="studentForm"></app-state>

<br/><br/>

<app-country [studentForm]="studentForm"></app-country>
<app-state [studentForm]="studentForm"></app-state> 

每个组件都可以访问相同的 属性 studentForm class。如果你想单独填充那个组件组那么你必须写这样的东西:

app.component.ts:

 this.studentForm = new FormGroup({
  'studentName':new FormControl(''),
  'countryId1': new FormControl(''),
  'stateId1': new FormControl(''),
  'countryId2': new FormControl(''),
  'stateId2': new FormControl('')
})

app.component.html:

<app-country [studentForm]="studentForm" [id]="'countryId1'"></app-country>
<app-state [studentForm]="studentForm" [id]="'stateId1'" [countryId]="'countryId1'"></app-state>

<br/><br/>

<app-country [studentForm]="studentForm" [id]="'countryId2'"></app-country>
<app-state [studentForm]="studentForm" [id]="'stateId2'" [countryId]="'countryId2'"></app-state>

并且在你的国家和州组件中分别使用countryId1/countryId2和stateId1/stateId2(还需要修改国家和州组件以使用'id'参数)。

更新

在country.component.ts中添加

@Input() id: string;

在state.component.ts中添加

@Input() id:string;
@Input() countryId:string;

get states(): State[]{
   var val = this.studentForm.controls[this.countryId].value;
   return this.selectService.filterStates(val);
};

在country/state.component.html改为:

<select [formControlName]="id">...

在select.service.ts中更改:

filterStates(countryId){
   if(!countryId) return null;
   return this.getStates().filter((item) => item.countryid == countryId);
}