I have a simple stepper with two steps.
On the first step there is a form with two radio inputs. I want to switch to the next step by clicking on one of the radio (without any submit buttons). I'm using stepper.next()
method to achieve this.
The problem is - it switching to the next step only after two clicks on the radio inputs.
Is there any way to switch to the next step by clicking only once?
Here's a demo with the problem https://angular-srtsoi.stackblitz.io
Editor: https://stackblitz.com/edit/angular-srtsoi?embed=1&file=app/stepper-overview-example.ts
Thats because you call stepper.next()
before your validity status on your form
updates to VALID
. So the stepper thinks your form is invalid and locks your step.
To handle this kind of race condition you can subscribe
to your formGroup statusChange
observable and call stepper.next()
when the status is valid:
import {Component, ViewChild} from '@angular/core';
import {MatStepper} from '@angular/material';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
/**
* @title Stepper overview
*/
@Component({
selector: 'stepper-overview-example',
templateUrl: 'stepper-overview-example.html',
styleUrls: ['stepper-overview-example.css']
})
export class StepperOverviewExample {
isLinear = true;
firstFormGroup: FormGroup;
@ViewChild('stepper') stepper: MatStepper;
constructor(private _formBuilder: FormBuilder) { }
ngOnInit() {
this.firstFormGroup = this._formBuilder.group({
firstCtrl: ['', Validators.required]
});
this.firstFormGroup.statusChanges.subscribe(
status => {
if (status === 'VALID') {
this.stepper.next();
}
console.log(status);
}
)
}
}
The validity status of your form hasn't been updated before you called stepper.next(). Since you have exclusively bound the code written in nextStepper() to the click event of the radio buttons, you can rest assured that it will be called only when the user clicks on either of the radio buttons. So, in a way you have already implemented the required validation yourself and do not need angular to perform the validation for you.
Solution 1: Replace
firstCtrl: ['', Validators.required] with the following code
firstCtrl: ['']
OR
Solution 2: Remove the error from the form control manually before calling stepper.next() like so
this.firstFormGroup.controls['firstCtrl'].setErrors(null)
stepper.next();
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