Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormControl boolean without default value in angular 2

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.

like image 795
martenolofsson Avatar asked Jun 19 '17 11:06

martenolofsson


People also ask

How do I change the default value in FormControl?

1. Default Value. If we want to set a default value to our form control, we can pass a default value while instantiating a FormControl in our class. city = new FormControl('Noida'); married = new FormControl(true);

What is difference between FormBuilder and FormControl?

In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.

How do I make a FormControl read only?

We use READONLY attribute to prevent user from type/select the form control but we get value from the input. We use DISABLED attribute to prevent user from type/select the form control and we dont get value from the input.


2 Answers

Only change Validators.required to Validators.requiredTrue, Something like:

payedOvertime: [false, Validators.requiredTrue]

like image 110
Azhr-M Avatar answered Oct 22 '22 14:10

Azhr-M


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.

like image 23
Vladimir Zdenek Avatar answered Oct 22 '22 14:10

Vladimir Zdenek