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()
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,
});
}
};
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With