0

I have a reactive form that has a table with a checkbox and some user inputs on each row. I want to make it so if the user checks a checkbox, the corresponding inputs need to be filled in. e.g. if 11+ is checked but the corresponding user inputs i.e. price is not filled out and the user attempts to press the add button, then it shouldn't submit the form and it and should provide a message. I'm not sure how to conditionally apply this logic.

Form in the TS:

this.addSubjectForm = new FormGroup({
  'type' : new FormControl(null, Validators.required),
  'subject' : new FormControl(null, Validators.required),
  'discount' : new FormControl(null),
  'levelDefinition' : new FormGroup({
    '11+' : new FormControl(null),
    'KS3' : new FormControl(null),
    'GCSE' : new FormControl(null),
    'A-Level' : new FormControl(null),
    'Degree' : new FormControl(null)
  })

HTML table/form:

<form [formGroup]="addSubjectForm" (ngSubmit)="onAddSubject()">
      <!-- the first three inputs (type, subject and discount) are not included here to reduce the amount of code shown in the question -->
      <div formGroupName="levelDefinition">
        <table class="table table-bordered table-condensed table-hover">
            <thead>
                <tr>
                  <th class="text-center">
                        <input type="checkbox" name="all" 
                        (change)="isSelected = !isSelected" />
                    </th>
                    <th>Level</th>
                    <th>Price</th>
                    <th>Discounts</th> 
                </tr>
            </thead>
            <tbody>
              <tr *ngFor="let level of levels ; let i = index">
                <td class="text-center" >
                    <input type="checkbox" 
                    value="{{level.id}}" 
                    appHighlightOnCheck
                    formControlName="{{level}}"
                    [checked]="isSelected" />
                </td>
                <td class="text-center">{{ level }}</td>
                <td>
                  <input
                  type="text"
                  class="form-control">
                </td>
                <td>
                  <input
                  type="text"
                  class="form-control">
                </td>
              </tr>
            </tbody>
          </table>
        </div>  
    </form>
    <button class="btn btn-primary" type="submit">Add</button>
Idris.AH
  • 410
  • 1
  • 10
  • 22
  • Perhaps you could use Custom Validators similar to this: https://stackoverflow.com/questions/31788681/angular2-validator-which-relies-on-multiple-form-fields – Ben Cottrell Apr 05 '18 at 22:36

1 Answers1

0

The way to do it is using cross-field custom validator. You will need to nest you 2 form controls with a form group (both in the ts and in the html). Then you need to build a custom validator and attach it to this formGroup.

Udi Mazor
  • 1,646
  • 2
  • 15
  • 30