如何从Angular表单中获取数据

时间:2019-06-24 14:46:27

标签: angular kendo-ui formarray

我想从表格中获取数据。我收到的数据不正确。我怎么了?

public editForm: FormGroup = new FormGroup({
    'id' : new FormControl(''),
    'name': new FormControl('', Validators.required),
    'code': new FormControl('', Validators.required),
    'active': new FormControl(),
    'sequence' : new FormControl(null),
    'entryTypes': new FormArray([new FormControl(), new FormControl()])
});
<div class="form-group">
    <label>
        <input type="checkbox" formArrayName="entryTypes" [checked]="locationEntryTypeDTOs[0].enabled"/>
        {{locationEntryTypeDTOs[0].entryTypeCode}}
     </label>
</div>

<div class="form-group">
    <label>
        <input type="checkbox" formArrayName="entryTypes" [checked]="locationEntryTypeDTOs[1].enabled"/>
        {{locationEntryTypeDTOs[1].entryTypeCode}}
    </label>
</div>

2 个答案:

答案 0 :(得分:1)

通过以下方式定义entryTypes数组。

<div class="form-group" formArrayName="entryTypes">
    <div *ngFor="let entryType of editForm.controls.entryTypes.controls; index as i">
        <label>
          <input type="checkbox" formControlName="{{i}}" />
          {{locationEntryTypeDTOs[i].entryTypeCode}}
        </label>
    </div>
</div>

并通过以下方式更新“ entryTypes”表单元素。并且,如果在locationEntryTypeDTOs中存储了更多的复选框和值,则必须创建一个单独的函数来启动“ entryTypes”。

'entryTypes': new FormArray([new FormControl(locationEntryTypeDTOs[0].enabled), new FormControl(locationEntryTypeDTOs[1].enabled)])

答案 1 :(得分:1)

<form [formGroup]="editForm">
  <div formArrayName="entryTypes">
      <input  [formControlName]="0">
      <input  [formControlName]="1">
  </div>
</form>

或者如果您想迭代

<form [formGroup]="editForm">
  <div formArrayName="entryTypes">
      <input *ngFor="let control of editForm.get('entryTypes').controls;
           let i=index" [formControlName]="i">
  </div>
</form>

其他形式

<form [formGroup]="editForm">
  <div formArrayName="entryTypes">
      <input *ngFor="let control of editForm.get('entryTypes').controls;
           let i=index" [formControl]="control">
  </div>
</form>