禁用表单数组中的反应形式选择表单控件

时间:2018-01-16 20:52:22

标签: angular angular-reactive-forms angular-forms form-control formarray

我试图通过检查被动形式的条件来禁用选择表单控件,而我无法在表单组件中动态地执行它。想知道以前是否有人这样做过?

let control = <FormArray>this.scheduleForm.controls.schedulingAvailability;
this.scheduleObj.schedulingAvailability.forEach(x => {
  control.push(this.formBuilder.group({
    day: x.day,
    startTime: x.startTime,
    status: x.status
  }))
  if(x.status) {
    this.scheduleForm.get('x.startTime').enable();
  } else {
    this.scheduleForm.get('x.startTime').disable();
  }
})

在我的组件中,我已将其设置为以下

<div formArrayName="schedulingAvailability">
    <div *ngFor="let d of scheduleForm.controls.schedulingAvailability.controls; let i=index">
        <div formGroupName="{{i}}">
            <div class="row">
                <div class="col-md-1">
                    <label class="checkbox">
                        <input type="checkbox" formControlName="status">
                        <span class="checkbox__input"></span>
                        <span class="checkbox__label">{{ scheduleObj.schedulingAvailability[i].day }}</span>
                    </label>
                </div>
            <div class="col-md-2">
                <div class="form-group__text select">
                    <select formControlName="startTime">

1 个答案:

答案 0 :(得分:0)

没有this.scheduleForm.get('x.startTime')这样的变量。 formArray startTime中存在schedulingAvailability。那么你需要在迭代中访问formarray的当前索引。那么你要做的是将forEach更改为for循环,以便我们可以获得当前迭代索引的保留:

let control = <FormArray>this.scheduleForm.controls.schedulingAvailability;

for (let i = 0; i < this.scheduleObj.schedulingAvailability.length; i++) {
  control.push(this.formBuilder.group({
    status: this.scheduleObj.schedulingAvailability[i].status,
    startTime: this.scheduleObj.schedulingAvailability[i].startTime
  }))

  // access the current formgroup of your formarray
  let fg = control.get([i])
  if (fg.get('status').value) {
    fg.get('startTime').enable();
  } else {
    fg.get('startTime').disable();
  }
}

StackBlitz

编辑:由于可以禁用该值,我们需要记住它不包含在表单值中。因此,如果您还想获取已禁用的值,请使用this.scheduleForm.getRawValue()