Angular 4 & Material Stepper

ⅰ亾dé卋堺 提交于 2019-12-03 11:02:24

问题


Is it possible to reset (or just jump to the first step) inside of a stepper? It is not documented in the docs, but is it possible to do so? It is stated in the docs that the stepper is built on "CDK Stepper" (link?), but I can't find any examples which lead me to my goal.


回答1:


Ok, it seems I found a solution (but it is not stated anywhere on the API).

  1. Add a reference to the stepper, then add ViewChild with the reference in your component typescript file.
  2. 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;
    }
}



回答2:


It is possible to jump to a specific stepper. MatStepper exposes a public property selectedIndex 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




回答3:


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


来源:https://stackoverflow.com/questions/46440642/angular-4-material-stepper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!