Reputation: 91
I have form control for selecting some value (for example - gender) and couple of <input type="radio">
.
The requirements are next:
My problem is that FormControl has just valueChanges event that emits after value was already changed. And I need to set up previous value programmatically:
this.genderControl.setValue(GenderEnum.MALE, {emitEvent: false});
Some pseudo code example:
component.html
<input
formControlName="gender"
type="radio"
value="female"
id="female"
/>
<input
formControlName="gender"
type="radio"
value="male"
id="male"
/>
<input
formControlName="gender"
type="radio"
value="other"
id="other"
/>
component.ts
this.genderControl.valueChanges
.pipe(
distinctUntilChanged(),
startWith(null),
pairwise(),
takeUntil(this._destroy$)
).subscribe(([prev, next]: [GenderEnum, GenderEnum]) => {
this.openWarningModal().afterClosed().subscribe((selectedAction: CommonModalsActionsEnum) => {
if (selectedAction === CommonModalsActionsEnum.CONFIRM) {
this.handleChangeGender(next);
}
if (selectedAction === CommonModalsActionsEnum.CLOSE) {
this.genderControl.setValue(prev, {emitEvent: false});
}
});
});
The possible solution may be in removing FormControl, using ngModel and subscription on input click event. In this way on click handler shows modal and changes or doesn't change the var, related to ngModel.
But I hope that the more clear solution is exist!
Upvotes: 0
Views: 1219
Reputation: 474
If you plan to use ngModel, instead of subscribing to the click event, you can subscribe to the
ngModelChanges()
event, which is the @Output of ngModel directive. It fires when the model changes.
Upvotes: 0