Angular4单选按钮绑定不适用于反应形式 [英] Angular4 radio button binding not working with reactive forms

查看:74
本文介绍了Angular4单选按钮绑定不适用于反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需从Angular2(我的代码可以正常工作)切换到Angular4.

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

我有一个true值绑定到我的一个单选按钮,但是在渲染视图时未选中该单选按钮.

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

以下代码的精简版:

我的组件:

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

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

视图:

<form [formGroup]="form">
    <input type="radio" class="form-control" formControlName="prop1" [value]="true"/>
    <input type="radio" class="form-control" formControlName="prop1" [value]="false"/>
</form>

推荐答案

如果您复制并粘贴OP的代码,则该代码有效.但这是因为patchValue行.如果删除patchValue,则不会选中该复选框,这是正确的行为.将[值]与反应形式一起使用会违反反应形式的目的.相反,使用patchValue是正确的.我很惊讶与angular2一起使用.

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.

但是,如果必须在模板中将其选中,则可以在[value] ="true"旁边使用[checked] ="true"或简单地将其作为常规属性进行选中.

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.

仍然,对于反应形式,使用FormControl API比使用属性更合适.

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

这篇关于Angular4单选按钮绑定不适用于反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆