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

时间:2019-01-03 10:33:17

标签: angular typescript angular7

我创建了一个用于管理级联国家和州的组件。如果我只形成一个国家和一个州,那么一切都会运转良好。但是,当我放置三个国家和州时,一切都在腐败,如下例所示。我该如何实现?

一个国家(工作示例)

Stackblitz

三个国家/地区(不作为示例)

Stackblitz

1 个答案:

答案 0 :(得分:1)

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

<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类的相同属性。如果要单独填充该组件组,则必须编写如下内容:

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);
}