David Jeyathilak
David Jeyathilak

Reputation: 111

disable reactive form select form control in a form array

I am trying to disable a select form control by checking a condition in a reactive form and I could not do it dynamically in my form component. Was wondering if anybody did this before?

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();
  }
})

And in my component, I have set-it up as following

<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">

Upvotes: 3

Views: 6080

Answers (1)

AVJT82
AVJT82

Reputation: 73357

There is no such variable as this.scheduleForm.get('x.startTime'). startTime is present in the formArray schedulingAvailability. So what you need to access that current index of the formarray in your iteration. So what you would do, is to change the forEach to a for loop instead, so that we can get the hold of the current index of the iteration:

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

Edit: As the value can be disabled, we need to remember that it's not included in the form values. So if you want to get the disabled values as well, use this.scheduleForm.getRawValue()

Upvotes: 1

Related Questions