I'm encountering a peculiar issue with radio buttons in my Angular application. Despite using separate FormControl
instances and unique for
and id
attributes for each pair of radio buttons, clicking on one radio button also selects the corresponding button in another pair.
Here's the simplified code snippet demonstrating the issue:
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { FormControl, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [FormsModule, ReactiveFormsModule, CommonModule],
template: `
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
<div>
<input id="foo" type="radio" [formControl]="formControl" [value]="true">
<label for="foo">foo</label>
<input id="bar" type="radio" [formControl]="formControl" [value]="false">
<label for="bar">bar</label>
</div>
<div>
<input id="foox" type="radio" [formControl]="formControl2" [value]="true">
<label for="foox">foox</label>
<input id="barx" type="radio" [formControl]="formControl2" [value]="false">
<label for="barx">barx</label>
</div>
{{formControl.value | json}}
`,
})
export class App {
name = 'Angular';
formControl = new FormControl();
formControl2 = new FormControl();
}
bootstrapApplication(App);
Could someone please assist in identifying why clicking on one radio button affects another despite having distinct FormControl
instances and unique identifiers for each radio button pair?
Currently, all radio buttons are treated as the same group.
Radio buttons are normally presented in radio groups (a collection of radio buttons describing a set of related options). Only one radio button in a group can be selected at the same time.
Hence, when you select one of the radio buttons from the row will affect the value (display) selection of the radio button in another row, although when you check the formControl2.value
it shows null
.
Thus, you need to provide the name
attribute to the radio button to represent the radio buttons in different groups.
Reference: HTML input type="radio"
<input id="foo" type="radio" [formControl]="formControl" name="group1" [value]="true">
<input id="bar" type="radio" [formControl]="formControl" name="group1" [value]="false">
<input id="foox" type="radio" [formControl]="formControl2" name="group2" [value]="true">
<input id="barx" type="radio" [formControl]="formControl2" name="group2" [value]="false">