FormControl boolean without default value in angular 2

martenolofsson picture martenolofsson · Jun 19, 2017 · Viewed 18.1k times · Source

I'm using reactive forms in 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:

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

Answer

Vladimir Zdenek picture Vladimir Zdenek · Jun 19, 2017

Change payedOvertime: [false, Validators.required] to 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). 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.