Home > Mobile >  Multiple radio button groups in one Angular Reactive form
Multiple radio button groups in one Angular Reactive form

Time:06-01

I see answers for this issue with Template forms. But none that address this scenario with FormGroups in Reactive Forms.

When I select a radio button from one form on the page, it deselects the default radio button in a completely separate form and FormGroup. Why is this, and how do I fix it? (I have deliberately separated everything, even the method call)

Here's the stackblitz: Stackblitz

CodePudding user response:

A radio buttons are grouped by name, In your example you are not providing any name so all the radio buttons are grouped as a single radio group.Add name to each radio button to avoid deselecting others.

<div >
  <input
    [id]="id"
    type="radio"
    [name]="name"
    [value]="value"
    [formControl]="ctrl"
    [checked]="checked"
  />
  <p>
    {{ label }}
  </p>
</div>

Forked Working Example

CodePudding user response:

In the basic HTML, the radio buttons are always grouped with name attribute, once all the radio buttons have the same name attribute they form a Radio Group. Here's the thing we have to do, take the name property as @Input() in your app-radio component and pass it to its template, when you want to use it as Radio Group, pass all the radio buttons in same group a same name value.

Here's the forked example of your app with fix. Stackblitz

And these are the few small changes we had to do, make this work.

// app-radio.ts
export class RadioComponent implements OnInit {
 @Input() label: string;
 @Input() ctrl: FormControl;
 @Input() value: string;
 @Input() id: string;
 @Input() name: string;
 @Input() checked: string;

 ngOnInit() {
    console.log('ctrl', this.ctrl);
 }
}


// app-radio.html
<input
 [id]="id"
 [name]="name"
 type="radio"
 [value]="value"
 [formControl]="ctrl"
 [checked]="checked"
/>

// app.html
<form [formGroup]="frm">
<app-radio id="rc1" name="frm" label="Inputs" value="Inputs" [ctrl]="getRadioOptions()" checked></app-radio>
<app-radio id="rc2" name="frm" label="HTML" value="HTML" [ctrl]="getRadioOptions()" ></app-radio>
<app-radio id="rc3" name="frm" label="Code" value="Code" [ctrl]="getRadioOptions()" ></app-radio>
</form>
<hr>

<form [formGroup]="frm2">
<app-radio id="rc4" name="frm2" label="Inputs2" value="Inputs2" [ctrl]="getRadioOptions2()" checked ></app-radio>
<app-radio id="rc5" name="frm2" label="HTML2" value="HTML2" [ctrl]="getRadioOptions2()" ></app-radio>
<app-radio id="rc6" name="frm2" label="Code2" value="Code2" [ctrl]="getRadioOptions2()" ></app-radio>
</form>
  • Related