Reputation: 668
I hope this image explains what I want to do.
So I want to do a custom radio component who share the same formControlName. When a radio is clicked, the rest of the components which share the same formControlName should update with active value.
How can I do it?
Upvotes: 5
Views: 725
Reputation: 1443
I've tested the behavior with only sharing formControlName between several inputs and it doesn't update based on this binding attribute alone. It looks like either workaround, ngModel (with v5 or older only) or a function is required to complete the desired behavior. A closed issue and some detailed dialog is available here:
https://github.com/angular/angular/issues/10036
Most notably:
Shared form controls are only supported right now for naturally grouped controls like radio buttons (which have a shared registry). For text inputs sharing controls, ngModel is the only option if you'd like them to be synced. We're not likely to add this functionality to reactive forms given the workaround, so closing. If you feel there is a use case for this that cannot be solved any other way, please feel free to open an issue with some more info about your use case.
But there are comments with workarounds.
The most attractive being:
a custom directive to force [FormControl] and [FormControlName] to update when the FormControl updates.
https://gist.github.com/Dyljyn/59e95fbe09a24b1835667a1a5e401e5a
You can create a function in the component that sets the value to your formControl:
setControl(value){
this.form.controlName = value
}
and do an on click event that calls the function:
<input type="radio" formControlName="controlName" (click)="setControl(x)">
Upvotes: 1