angular: Cannot select multiple radio buttons in same control group

In beta.6 when having multiple radio buttons in the same control group, as soon as one is selected all the others in that same control group get updated to unchecked, even though they have a different name. The issue seems related to this line in RadioControlRegistry:

      if (c[0].control.root === accessor._control.control.root && c[1] !== accessor) {
        c[1].fireUncheck();
      }

Shouldn’t it check that they match the name?

      if (c[0].control.root === accessor._control.control.root 
        && c[1] !== accessor && c[1].name === accessor.name) {
        c[1].fireUncheck();
      }

Thanks

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 15 (3 by maintainers)

Commits related to this issue

Most upvoted comments

The bug still remains in 2.0.0-rc.1 😦

@mdymel To get around it, I am injecting a custom implementation of RadioControlRegistry

import {RadioControlRegistry, RadioControlValueAccessor} from 'angular2/src/common/forms/directives/radio_control_value_accessor';

// TODO Monkey patching Radio buttons until https://github.com/angular/angular/issues/7051 is fixed
export class CustomRadioControlRegistry extends RadioControlRegistry {

    select(accessor: RadioControlValueAccessor) {
        (<any>this)._accessors.forEach((c) => {
            if (c[0].control.root === accessor._control.control.root
              && c[1] !== accessor && c[1]._elementRef.nativeElement.name === (<any>accessor)._elementRef.nativeElement.name) {
              c[1].fireUncheck();
            }
        });
    }
}

And then when bootstrapping the app, I am replacing the RadioControlRegistry with my implementation: provide(RadioControlRegistry, {useClass: CustomRadioControlRegistry})

Hmm, I’m not doing that, so maybe I’ll be OK relying on that name property. I would also like to suggest that this issue transcends control groups. The way I see it, using root as the discriminator will affect all radio buttons in the same form. My first attempt at working around this was to create a separate subgroup for each desired radio group, i.e, instead of:

this.form = fb.group({
  ...
  // these two have name="a" on their corresponding HTML elements
   'a1': [new RadioButtonState(false, 'a1')],
   'a2': [new RadioButtonState(false, 'a2')],
...
  // these two have name="b"
   'b1': [new RadioButtonState(false, 'b1')],
   'b2': [new RadioButtonState(false, 'b2')],
...
}

I tried:

this.form = fb.group({
  ...
  'a': fb.group({
   'a1': [new RadioButtonState(false, 'a1')],
   'a2': [new RadioButtonState(false, 'a2')],
}),
...
'b': fb.group({
   'b1': [new RadioButtonState(false, 'b1')],
   'b2': [new RadioButtonState(false, 'b2')],
})
...
}

and changing the corresponding ngFormControl bindings to add the additional level of indirection. This didn’t help. Selecting any radio button in either group deselected all other buttons, even the ones in other groups.