您有两个引用相同变量的元素:
<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);
}