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>
3
  • The code is good. Is there anything else going, any errors showing in the debugger? Commented May 5, 2017 at 4:06
  • make sure you have update all angular packages to 4.0.0+ . your code works good here. plnkr.co/edit/AoZeEafOduYf3VT6DISV?p=preview Commented May 5, 2017 at 4:09
  • @raneshu do you have a solution for that problem? I have the same problem as you with reactive forms. See: stackoverflow.com/questions/42614531/… Commented Jul 17, 2017 at 20:50

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.