Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when mat-stepper validation fails

We have a linear mat-horizontal-stepper now we want to show a MatSnackBar when the user tries to proceed an forgot a required field.

CdkStepper seems to call _anyControlsInvalidOrPending silently and returns if any input is not valid.

Does anybody have an idea how to detect this event?

It must be detected when calling stepper.next(), stepper.previous() and step.select()

like image 796
wutzebaer Avatar asked Oct 22 '25 04:10

wutzebaer


2 Answers

A dirty solution would be

  ngAfterViewInit() {
    // when clicking on the step header
    this.stepper._steps.forEach((step) => {
      this.addPriorValidyCheckToFunction(step, 'select');
    });
    // when calling previous and next function
    this.addPriorValidyCheckToFunction(this.stepper, 'next');
    this.addPriorValidyCheckToFunction(this.stepper, 'previous');
  }

  addPriorValidyCheckToFunction(object, functionName) {
    // keep reference to AppComponent
    let self = this;
    // keep reference to original function
    let oldFunction = object[functionName];
    // replace original function
    object[functionName] = function () {
      // remember step before calling the function
      let oldStep = self.stepper.selected;
      // call the original function
      oldFunction.call(object);
      // if step did not change and form is invalid, show the message
      if (oldStep == self.stepper.selected && !self.stepper.selected.stepControl.valid) {
        self.snackBar.open("Fehler", "Bitte überprüfen Sie Ihre Eingaben", {
          duration: 2000,
        });
      }

    };
  }
like image 160
wutzebaer Avatar answered Oct 23 '25 20:10

wutzebaer


You need to add a "linear" attribute

<mat-vertical-stepper linear>

This will disable from navigating to next step if the form is invalid. Then add your validation function on click of the button if form is invalid then you can show alert or snackbar or whatever you want.

like image 42
Vishal Hulawale Avatar answered Oct 23 '25 19:10

Vishal Hulawale