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.
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);
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.
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.
Only change Validators.required
to Validators.requiredTrue
,
Something like:
payedOvertime: [false, Validators.requiredTrue]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With