[Angular Material] Setpper自動跳到沒有填寫正確的step去

 

Material Angular: automatic scroll to invalid Input and open matstepper

https://stackoverflow.com/questions/61368368/material-angular-automatic-scroll-to-invalid-input-and-open-matstepper


Using mat-stepper instance you can get the form status. Then we can navigate to invalid step programeticaly. First in order to get mat-stepper instance you have to place #stepper template varibale on mat-vertical-component like this:

<mat-vertical-stepper #stepper [linear]="isLinear">

Now add ViewChild in your ts like this to get stepper instance:

@ViewChild('stepper') private myStepper: MatStepper;

Finally you can check individual form status using stepControl property like this and navigate to invalid step by setting selectedIndex

 scrollToError(): void {
    const steps = this.myStepper._steps.toArray();
     for(let i = 0; i < steps.length -1; i++ ){
        if(!steps[i].stepControl.valid){
       this.myStepper.selectedIndex = i;  
       return ;
    }
  }

Forked Example


https://stackblitz.com/edit/angular-material-stepper-xz8n8m








留言

這個網誌中的熱門文章

[Angular] 閒置登出作法

[JavaScript] 將array object 根據值重新 js format的作法