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)

2
  • 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. Commented Apr 8, 2019 at 16:37
  • Does this answer your question? How to set value to form control in Reactive Forms in Angular Commented Jan 2, 2020 at 19:12

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.