Roman Leliuk
Roman Leliuk

Reputation: 91

Angular, FormControl - confirm value change

I have form control for selecting some value (for example - gender) and couple of <input type="radio">. The requirements are next:

  1. When user changes the input, I need to show a modal window which asks him to confirm or cancel changes (without doing anything).
  2. I need to show modal only if user changes input value from one gender to another.

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

Answers (1)

Gauri Kesava Kumar
Gauri Kesava Kumar

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

Related Questions