【发布时间】:2021-02-02 20:44:16
【问题描述】:
我有一个包含复选框列表的表单,如果其中一个被选中,则会显示输入表单。
这是我的 component.ts :
coveragestypes : Array<ItemPolicyModel>= [{id:'1', name :'type 1'},{id : '2',name :'type 2'},{id : '3',name :'type 3'},{id:'4',name:'type 4'}]
policyForm = new FormGroup({
coverages :new FormArray([]),
coveragesValue:new FormArray([]),
})
ngOnInit() {
this.names = this.coveragestypes.map(x => x.name)
this.addCheckboxes();
}
addCheckboxes() {
this.names.forEach(() => this.coverageFormArray.push(new FormControl()));
this.names.forEach(() => this.coveragesValueFormArray.push(new FormControl('', Validators.pattern(/^-?(0|[1-9]\d*)?$/))));
}
get coverageFormArray() {
return this.policyForm.controls.coverages as FormArray;
}
get coveragesValueFormArray() {
return this.policyForm.controls.coveragesValue as FormArray;
}
这是我的html:
<div class="checkbox">
<label formArrayName="coverages"
*ngFor="let coverage of coverageFormArray.controls;let i = index; ">
<input type="checkbox" kendoCheckBox [formControlName]="i" />
{{names[i]}}
<ng-container *ngIf="coverage.value">
<input type="text" [formControl]="policyForm.get('coveragesValue.'+i)">
</ng-container>
</label>
</div>
当我控制 policyForm 值时,它会像这样保存:coverages: (4) [true, true, false, false] coveragesValue: (4) ["123", "555", "", ""] 或者我希望它像这样保存在一个表单数组中:
coverages : [{id : '1', name : 'type1', value : '123'},{id : '2', name : 'type2', value : '555'}]
谁能帮帮我!
【问题讨论】:
标签: angular angular-reactive-forms