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();
};
}