Angular 4 & Material Stepper
Ok, it seems I found a solution (but it is not stated anywhere on the API).
- Add a reference to the stepper, then add
ViewChild
with the reference in your component typescript file. - Create a method to change the index of the stepper.
HTML:
<mat-horizontal-stepper [linear]="true" #stepper>
<!-- Content here -->
</mat-horizontal-stepper>
TS:
import { Component, ViewChild } from '@angular/core';
@Component({
// ...
})
export class AppComponent {
@ViewChild('stepper') stepper;
/**
* Changes the step to the index specified
* @param {number} index The index of the step
*/
changeStep(index: number) {
this.stepper.selectedIndex = index;
}
}
It is possible to jump to a specific stepper.
MatStepper
exposes a public propertyselectedIndex
which specifies the currently selected step index. It can be set. The index starts at 0.
In your template:
Add an id to your stepper e.g. #stepper
. Then add a button in your step, and pass the stepper id in a function on (click)
like below:
<mat-horizontal-stepper [linear]="isLinear" #stepper>
<!-- Your other steps here -->
<mat-step [stepControl]="secondFormGroup">
<!-- Content in the step -->
<div>
<!-- Other actions here -->
<button mat-button (click)="resetStepper(stepper)">Reset</button>
</div>
</mat-step>
<!-- More steps here -->
</mat-horizontal-stepper>
.. and in your typescript:
import { MatStepper } from '@angular/material';
exported YourOwnComponent {
constructor() {}
resetStepper(stepper: MatStepper){
stepper.selectedIndex = 0;
}
}
Stackblitz demo
In the html template , reference your stepper with #stepper
<mat-horizontal-stepper #stepper>
</mat-horizontal-stepper>
and in your typescript file declare the stepper
@ViewChild("stepper", { static: false }) stepper: MatStepper;
after that you can set the stepper step with his selectedIndex property
this.stepper.selectedIndex = 0; //0 is the index of the first step