Disable input on FormArray with checkbox

822 Views Asked by At

I have a multi-step form

1

Where in the third step you can add a FormArray with your schools. I have an input date ''fechaFin'' (endDate) which if you're currrently in the school you can check the checkbox ''En Curso'' (in progress) so the input change to disabled.Here you can see if it's checked the input change to disabled.

2

This is the method that change the input to enable or disable.

  checkBoxChange(e: Event) {
    const isCheck = (<HTMLInputElement>e.target).checked
    if (isCheck == true){
      this.thirdFormGroup.controls['fechaFin'].disable();
    } else {
       this.thirdFormGroup.controls['fechaFin'].enable();
    }
  }

The thing is that clicking the button ''Haga click para agregar Estudios'' I add a new form array with the 4 inputs and the checkbox but if I check any of the checkbox it disables or enables all the endDate inputs. I've been trying different ways but I'm not sure how to change just the input of the form array I'm checking. Here you can see that checking the first one it disables both input.

3

This is my HTML file showing just the input and the checkbox.

<div class="row justify">
  <div class="col-md-4">
    <mat-form-field appearance="fill">
      <mat-label>Fecha Fin</mat-label>
      <input id="endDate" class="dates" matInput type="date" placeholder="Feha de nacimiento" formControlName="fechaFin" required>
    </mat-form-field>
  </div>
  <div class="col-md-2">
    <input type="checkbox" (change)="checkBoxChange($event)" name="enCurso" id="enCurso">
    <label class="checkEnCurso" for="enCurso">En curso.</label>
  </div>
</div>
1

There are 1 best solutions below

1
Guiditox On

Welcome.

It seems that you are not using formArray on the correct way.

In this case, the structure about thirdFormGroup it has to be something like that:

this.thirdFormGroup = this.formBuilder.array([{
  fechaFin: [null,Validators.Required]
  fechaDesde: [null]
}])

Then, you have to enable just one index from your formArray

Something like that:

  checkBoxChange(e: Event,index) {
    const isCheck = (<HTMLInputElement>e.target).checked
    if (isCheck == true){
      this.thirdFormGroup[index].controls['fechaFin'].disable();
    } else {
       this.thirdFormGroup[index].controls['fechaFin'].enable();
    }
  }

Did you see the difference?

thirdFormGroup is not just a formGroup, it has to be a formArray.

If you need an example, just let me know and I can update my comment.