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:
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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.