Angular4 radio button binding not working with reactive forms

瘦欲@ 提交于 2019-12-12 05:59:42

问题


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>

回答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.



来源:https://stackoverflow.com/questions/43796055/angular4-radio-button-binding-not-working-with-reactive-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!