1

My angular reactive form is not able to set the UI state of the radio button, I'm trying to load a from state for a 'saved search' feature of an app

I'm using angular 7 and angular material

//declaration
    this.filterForm = new FormGroup({
      heating: new FormControl('1'),
    });
//loadSearch fuction
  this.filterForm.setValue(valueObject);
  <label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="heating-1" >
          <input formControlName="heating" id="heating-1" type="radio" name="heating" (change)="onFilterCheckChange($event,'heating')" class="mdl-radio__button"  [value]=1 checked>
          <span class="mdl-radio__label">Si</span>
        </label>
        <label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="heating-2" >
          <input formControlName="heating" id="heating-2"  type="radio" name="heating" (change)="onFilterCheckChange($event,'heating')" class="mdl-radio__button"  [value]=0 >
          <span class="mdl-radio__label">No</span>
        </label>

Expected result is that form UI gets updated when i call .setValue in loadSearch fuction, actual result is that nothing happens to the UI (but the formControl object has the correct value)

rastrano
  • 123
  • 3
  • 6
  • 2
    1. Put double quotes around your HTML attribute values. 2. Don't use `checked`: Angular decides what to check based on the model, which is the source of truth. 3. What is the value of `valueObject`? 4. You initialize the control with the string '1', but the two possible values are the numbers 0 and 1. Post a complete minimal example reproducing the problem, as a stackblitz. – JB Nizet Apr 08 '19 at 16:37
  • Does this answer your question? [How to set value to form control in Reactive Forms in Angular](https://stackoverflow.com/questions/55275025/how-to-set-value-to-form-control-in-reactive-forms-in-angular) – wentjun Jan 02 '20 at 19:12

1 Answers1

4

Basically, you have two ways:

You can: Set the value for the entire form: so your valueObject would override the value you provided in the declaration and, if the only form field was heating, you'd have something like this:

this.filterForm.setValue({
  heating: '0' // or 1
});

Or: Set the value just for the heating field:

this.filterForm.controls.heating.setValue('0');

Also, please make sure that radio value types match with the data you are initialising and setting, so you might want to use string type in the input and also get rid of the checked property.

Hope this helps!

Hawz
  • 4,027
  • 1
  • 10
  • 11