问题
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?
回答1:
As per the The data model and the form model guide for Reactive Forms
User changes flow from the DOM elements to the form model, not to the data model. The form controls never update the data model.
Which means that when user select any value from radio your variable this.variable.isRequired
is not get updated. To get form value you have to use this.myForm.value
or you have to use ngModel
on radio as explained on ng-bootstrap buttons.
回答2:
I realized that this problem is caused by popper.js The official documentation of ng-bootstrap strongly advises against including it.
Please read the documentation provided here.
来源:https://stackoverflow.com/questions/47388377/two-way-binding-not-working-in-ng-bootstrap-radio-button-in-an-angular-reactive