raneshu
raneshu

Reputation: 413

Angular4 radio button binding not working with reactive forms

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>

Upvotes: 0

Views: 2501

Answers (1)

Eeks33
Eeks33

Reputation: 2315

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.

Upvotes: 1

Related Questions