form valueChanges on second step only

Viewed 98

I am using mat-stepper with single form. I have two steps only. I want to do API request on every input value change but only when the user is on the second step. how can I achieve that?

.ts

  ngOnInit() {
    this.formGroup = this._formBuilder.group({
      formArray: this._formBuilder.array([
        this._formBuilder.group({
          "product": ['lifeci', Validators.required],
          "gender": ['', Validators.required],
          "birthDate": ['', [Validators.min(18), Validators.max(50)]],
          "payFrequency": [12],
          "subLimit": ['100']
        }),
        this._formBuilder.group({
          "currency": ['USD', Validators.required],
          "amount": ['15000', Validators.required],
          "period": ['', Validators.required],
        }),
      ])
    });
    //send request onchange
    this.formGroup.valueChanges.subscribe(val => {
      this.onSubmit();
    });
  }

for the HTML I am using the same structure as from documentation.

3 Answers

You can subscribe only to the second step part of the form

(this.formGroup.get('formArray') as FormArray).at(1).valueChanges.subscribe(val => {
      this.onSubmit();
    });
  }

First, add an extra variable selectedTabIndex in your TS.

const selectedTabIndex = 0;

Then, add selectedIndex input directive to your stepper like:

<mat-horizontal-stepper [selectedIndex]="selectedTabIndex">

Finally, change in the valueChanges subscription as:

this.formGroup.valueChanges.subscribe(val => {
    if (selectedTabIndex === 1) {// That means second tab is selected
        this.onSubmit();
    }
});

To clearly understand on which form you operate it is good practice to extract from each step "semi-form" into getter.

In your component file declare enum or type that describes each step.

enum FormStep {
  BorrowerDetails = 0,
  LoanDetails = 1
}

In your component class declare getters for each step.

private get debeterDetailsForm() {
  return (this.formGroup.get('formArray') as FormArray).at(FormStep.BorrowerDetails);
}

private get loanDetailsForm() {
  return (this.formGroup.get('formArray') as FormArray).at(FormStep.LoanDetails);
}

Then in your component after declaring form you can use declared getters.

this.loanDetailsForm.valueChanges.subscribe(() => this.onSubmit());
Related