angulartypescriptmat-stepper

How to detect mat-stepper start and end in Angular?


currently, I have a vertical mat-stepper. it fills the steps using a *ngFor.

<mat-step [stepControl]="firstFormGroup" *ngFor="let stream of selectedStreamList; let indexOfelement = index;">

So, I want to detect the start of this stepper and end of this stepper to use as a variable. currently, I'm using a variable as a counter. I increment and decrement it to detect the mat step. but I want a good solution that that. So is there anyone that can help me with this matter?


Solution

  • The mat-stepper emits a selectionChange event every time the step changes. You can subscribe to these changes inside of your typescript file and handle accordingly...something maybe like this.

    //app.component.ts
    
    import { Component, ViewChild, AfterViewInit } from "@angular/core";
    import { MatStepper } from "@angular/material/stepper";
    import { StepperSelectionEvent } from "@angular/cdk/stepper";
    import { pluck } from "rxjs/operators";
    
    @Component({
      selector: "app-root",
      template: `
        <mat-vertical-stepper #stepper>
          <mat-step
            *ngFor="let stream of selectedStreamList; let indexOfelement = index"
          ></mat-step>
        </mat-vertical-stepper>
      `
    })
    export class AppComponent implements AfterViewInit {
      @ViewChild("stepper", { static: false }) private stepper: MatStepper;
    
      selectedStreamList = [1, 2, 3, 4];
      isAtStart: boolean;
      isAtEnd: boolean;
    
      constructor() {}
    
      ngAfterViewInit() {
        this.stepper.selectionChange
          .pipe(pluck("selectedIndex"))
          .subscribe((res: number) => {
            this.isAtStart = res === 0;
            this.isAtEnd = res === this.selectedStreamList.length - 1;
          });
      }
    }