简体   繁体   English

角度2中没有默认值的FormControl布尔值

[英]FormControl boolean without default value in angular 2

I'm using reactive forms in angular 2 (4.1.2)我在 angular 2 (4.1.2) 中使用反应形式

I have a boolean property which I don't want to have a default value but it should be required.我有一个布尔属性,我不想有默认值,但应该是必需的。

This is how I create my form:这就是我创建表单的方式:

constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
        payedOvertime: [false, Validators.required],
    });
}

And my html:还有我的 html:

<div class="form-group">
    <label>Payed overtime</label>
    <label>
        <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="true" />Yes
    </label>
    <label>
        <input type="radio" name="payedOvertime" formControlName="payedOvertime" [value]="false" />No
    </label>
</div>

The problem is that while this works the radiobutton is preselected but I do not want that, rather it should have to be selected by clicking at one of the radio-buttons.问题是,虽然这行得通,但单选按钮是预选的,但我不希望那样,而是必须通过单击其中一个单选按钮来选择它。 If neither of the radiobuttons are clicked I want the form to be invalid.如果没有单击两个单选按钮,我希望表单无效。

Change payedOvertime: [false, Validators.required] to payedOvertime: [null, Validators.required] .payedOvertime: [false, Validators.required]更改为payedOvertime: [null, Validators.required]

Given that you set it to false , it matches the value of No radio button in the template and it selects it by default (rightly so).鉴于您将其设置为false ,它匹配模板中No单选按钮的值,并且默认情况下选择它(正确的)。 Setting it to null will prevent Angular from matching the value with any of those declared in the template and thus non of those radio buttons will be selected.将其设置为null将阻止 Angular 将该值与模板中声明的任何值进行匹配,因此将不会选择这些单选按钮。

仅将Validators.required更改为Validators.requiredTrue ,例如:

payedOvertime: [false, Validators.requiredTrue]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM