Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  91] [ 2]  / answers: 1 / hits: 36015  / 7 Years ago, mon, june 19, 2017, 12:00:00

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.


More From » angular

 Answers
25

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.


[#57389] Saturday, June 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazmyne

Total Points: 503
Total Questions: 102
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;