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

查看:21
本文介绍了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.

代码的精简版如下所示:

Condensed version of code shown below:

我的组件:

// 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,则不会选中该复选框,这是正确的行为.将 [value] 与反应形式一起使用与反应形式的目的背道而驰.改用 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天全站免登陆