I have a Material Angular Stepper (here a stackblitz running example) and I would like to reset the form on each step when the step is loaded.
I found in the Material Angular docs
that we can use reset() method on MatStep to
Resets the step to its initial state. Note that this includes resetting form data.
But, each time I call this method, it generates an error : Error: list is undefined
Here, a stackblitz running example
app.component.html,
<h1>{{ name }}</h1>
<hr />
<mat-stepper
#stepper
class="flex-grow-1"
(selectionChange)="reloadStep($event)"
>
<mat-step #s1>
<ng-template matStepLabel>Username</ng-template>
<ng-template matStepContent>
<form>
<input type="text" placeholder="Username" />
</form>
</ng-template>
</mat-step>
<mat-step #s2>
<ng-template matStepLabel>Something else </ng-template>
<ng-template matStepContent>
<form>
<input type="text" placeholder="Something else ..." />
</form>
</ng-template>
</mat-step>
</mat-stepper>
app.component.ts,
import { Component, AfterViewInit, ViewChildren} from '@angular/core';
import { MatStepper, MatStep } from '@angular/material/stepper';
import { StepperSelectionEvent } from '@angular/cdk/stepper';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
name = "Material Angular Stepper";
@ViewChildren('stepper') stepper!: MatStepper;
@ViewChildren('s1') one!: MatStep;
@ViewChildren('s2') two!: MatStep;
steps: MatStep[] = [];
ngAfterViewInit(): void {
this.steps = [this.one, this.two];
}
reloadStep = (stepperEvent: StepperSelectionEvent) => {
const index = stepperEvent.selectedIndex;
console.log('step changed:', index);
this.steps[index].reset();
};
}
There are some changes you must make in your code for it to work as you expect.
First of all, if you just want to reset the selected step, you can do it in the
reloadStepdirectly, without the need for theMatSteparray. This eliminates thelist is undefinederror:For the form resetting part, that needs some extra work. If you are not familiarized with Reactive Forms, this part may be a little confusing. Start by importing the
ReactiveFormsModulein yourAppModuleor the corresponding module:Then, in your
component.tsyou need to create twoFormGroupinstances. I'll just put the relevant parts of the code here:Last but not least, in the template you have to specify the
[stepControl]input property of eachMatStep,[formGroup]input property of each form andformControlNameof each input control to match the name of the control defined in yourcomponent.tsfile:Only then, each time you select a step, it is reset as well as the corresponding form.
Here's a modified Stackblitz: https://stackblitz.com/edit/angular-ivy-cwkqzx?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts,src%2Fapp%2Fapp.module.ts