如何以反应形式创建复杂的表单控件 angular

How to create a complex form control in reactive form angular

我有一个包含复选框列表的表单,如果其中一个被选中,则会显示输入表单。

这是我的 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'}]

谁能帮帮我!

实现 formArray.value 给出正确对象数组表示的一种方法

coverageExample: Record<String,any> = {id : '1', name : 'type1', value : '123'};
coverageTypes: Record<String,any>[] = [coverageExample];

将用 formGroups 的 formArray 来表示这些对象。 一些 formControls 将仅用于存储对象值。

// ...
addCheckboxes() {

    let formGroups: FormGroup[] = this.coveragestypes.map((coverage) => {
            return new FormGroup({
                    id: new FormControl(coverage.id),
                    name: new FormControl(coverage.name),
                    value: new FormControl('', Validators.pattern(/^-?(0|[1-9]\d*)?$/))
                    checked: new FormControl(false)});
        });
    this.coverageFormArray = new FormArray(formGroups);
}
// ...

使用这种结构 coverages.value 应该 return 您想要的对象。 标记需要更新如下

<div class="checkbox">
    <div *ngFor="let coverage of coverageFormArray.controls;let i = index; ">
        <div [formGroup]="coverage">
            <input type="checkbox" kendoCheckBox [formControl]="coverage.controls.checked" />
    {{coverage.controls.name.value}}        
            <ng-container *ngIf="coverage.controls.checked.value">*
                Value:
                <input type="text" [formControl]="coverage.controls.value">
          </ng-container>
        </div>
    </div>
</div>
// ...

编辑:修复了一些标记并添加了 stackblitz

https://stackblitz.com/edit/how-to-create-a-complex-form-control?file=src/app/app.component.ts