Search code examples
angulartypescriptradio-buttonangular-reactive-forms

Set value of a button used as a radio button programmatically


I am trying to set a value of a button which is used as a radio button via code. I am using reactive forms.

I tried setting the initial value of the buttons on ngOnInit

ngOnInit() {
  this.form = this.fb.group({
    radioOption: ['optionA'], // Set the initial value to 'optionA'
    selectedFood: ['Peach'], // Set the initial value to 'Peach'
  });
  this.form.patchValue({
    selectedFood: '',
  });
}

and via the button click to call 'Set'

setPeachValue() {
  console.log('setting value');
  this.form.patchValue({
    selectedFood: 'Peach',
    radioOption: 'optionA',
  });
}

Both methods yield the same result, I am unable to set the value of the buttons 'Option A' & 'Option B'.

StackBlitz for reference.


Solution

  • The reactive form set value for the radioOption control works correctly. But the issue came from it is not able to add the "active" class to the button toggle.

    You need to add the "active" class to the button toggle based on the value via [ngClass].

    And note that it is not recommend to use [(ngModel)] as you are using the Reactive form, it is redundant and may leads to unexpected behavior for the value.

    <label
      class="btn btn-secondary"
      tabindex="0"
      [ngClass]="{ active: form.get('radioOption').value === 'optionA' }"
    >
      <input
        type="radio"
        name="options"
        id="optionA"
        [formControl]="form.get('radioOption')"
        autocomplete="off"
        [value]="'optionA'"
      />
      Option A
    </label>
    <label
      class="btn btn-secondary"
      tabindex="0"
      [ngClass]="{ active: form.get('radioOption').value === 'optionB' }"
    >
      <input
        type="radio"
        name="options"
        id="optionB"
        [formControl]="form.get('radioOption')"
        autocomplete="off"
        [value]="'optionB'"
      />
      Option B
    </label>
    

    Demo @ StackBlitz