I am developing an application with Angular 4, Bootstrap 4 and ngbootstrap. The html code -
<div class="container">
<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value)">
<div class="form-group">
<div class="row">
<legend class="col-form-legend col-sm-2">Required</legend>
<div class="btn-group col-sm-2" ngbRadioGroup name="isRequired" formControlName="isRequired">
<label ngbButtonLabel class="btn-primary">
<input ngbButton type="radio" name="radio" [value]="true">Yes
</label>
<label ngbButtonLabel class="btn-primary">
<input ngbButton type="radio" name="radio" [value]="false">No
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6">
<button type="submit" class="btn btn-info">
<i class="fa fa-floppy-o fa-lg"></i>
Save
</button>
</div>
</div>
</form>
</div>
The controller
private buildForm() {
this.myForm = this.formBuilder.group({
isRequired: [],
});
}
In the ngOnInit() hook of the controller I call the buildForm() method. Then I make a Http get request and fetch a value for the isRequired field. If the fetch is successful I call the following method to set the value of the radio button.
private loadFormData() {
this.myForm.patchValue({
isRequired: this.variable.isRequired,
});
}
The problem - Lets assume the value of isRequired = true. This value gets fetched properly and the radio gets initialized with this value on form load. However, if the user changes the value (isRequired = false) the field still retains the previous value (isRequired = true).
This works fine if I use the following code -
<div class="form-group">
<div class="row">
<legend class="col-form-legend col-sm-2">Required</legend>
<input type="radio" formControlName="isRequired" value="true"> Yes
<input type="radio" formControlName="isRequired" value="false"> No
</div>
</div>
What am I doing wrong?