3

I try to create a reactive form of this kind:

(o) Some radio button
( ) Another radio button
    [ ] A nested checkbox, disabled as long "Another radio button" is not selected
    [ ] Another checkbox, disabled as long "Another radio button" is not selected

The checkboxes are disabled in the state shown above. If the second radio button is activated, the checkboxes can also be selected.

How do I model that in Angular.io with reactive forms? One could view it as a single control, with values:

  • artificial value representing selection of first radio button
  • value of first checkbox
  • value of second checkbox

Another way would be that it is a boolean FormControl, but in case of one value another FormControl is added below, but I don't think this is possible.

What is the best way to model that in reactive forms logic?

1 Answer 1

2

If your checkbox options are fixed then you could create a nested FormGroup for the "Another radio button" options in the ngOnInit:

  ngOnInit() {
    this.form = this.fb.group({

      radioGroup: '0',
      ckBoxGroup2: this.fb.group({
        ckBoxG2_1: { value: false, disabled: true },
        ckBoxG2_2: { value: false, disabled: true },
      })
    });

Then in the same ngOnInit method subscribe to valueChange Observable of the radio button control. Of course, the are other ways to react to changes but I like this:

    this.form.get('radioGroup').valueChanges.subscribe(value => {
      value === '2' ? this.form.get('ckBoxGroup2.ckBoxG2_1').enable() : this.form.get('ckBoxGroup2.ckBoxG2_1').disable();
      value === '2' ? this.form.get('ckBoxGroup2.ckBoxG2_2').enable() : this.form.get('ckBoxGroup2.ckBoxG2_2').disable();
    });

In the template create the same structure:

<form [formGroup]=form>

  <input type="radio" value="1" formControlName="radioGroup">Group 1<br />

  <input type="radio" value="2" formControlName="radioGroup">Group 2
  <div formGroupName="ckBoxGroup2" style="margin-left: 20px" >
    <div>
      <label>CheckBox 1
        <input type="checkbox" formControlName="ckBoxG2_1">
      </label>
    </div>
    <div>
      <label>CheckBox 2
        <input type="checkbox" formControlName="ckBoxG2_2">
      </label>
    </div>
  </div>

</form>

Check this demo I made based on your example: https://stackblitz.com/edit/angular-cfcznq

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, now I start to understand. I was too much focused on how the controls are shown to the user and I tried to mimic that in the way I design the FormControl structures :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.