0

Just switched from Angular2 (where my code worked with no problem) to Angular4.

I have a true value bound to one of my radio buttons, but the radio button is not selected when the view renders.

Condensed version of code shown below:

My component:

// all relevant imports...
...
export class My Component{
    public form: FormGroup = this.formBuilder.group({ prop1: ''});

    constructor(private formBuilder: FormBuilder){
        this.form.patchValue({prop1: true});
    }
}

view:

<form [formGroup]="form">
    <input type="radio" class="form-control" formControlName="prop1" [value]="true"/>
    <input type="radio" class="form-control" formControlName="prop1" [value]="false"/>
</form>
raneshu
  • 363
  • 2
  • 16
  • 46
  • The code is good. Is there anything else going, any errors showing in the debugger? – JayChase May 05 '17 at 04:06
  • make sure you have update all angular packages to 4.0.0+ . your code works good here. https://plnkr.co/edit/AoZeEafOduYf3VT6DISV?p=preview – Pengyy May 05 '17 at 04:09
  • @raneshu do you have a solution for that problem? I have the same problem as you with reactive forms. See: https://stackoverflow.com/questions/42614531/how-to-set-the-selected-radio-button-initially-in-ngfor-on-radiobutton-group – Pascal Jul 17 '17 at 20:50

1 Answers1

1

The code works if you copy and paste OP's code. But that's because of the patchValue line. If you remove patchValue, the checkbox will not be checked, which is the correct behaviour. Using [value] with reactive forms goes against the purpose of reactive forms. Using patchValue instead is correct. I'm surprised this worked with angular2.

If however you must have it checked in the template, you can use [checked]="true" alongside [value]="true" or simply have checked as a regular attribute.

Still, with reactive forms it is more appropriate to use the FormControl API's than the attributes.

Eeks33
  • 2,245
  • 1
  • 14
  • 17