[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] 回到最上面 goTop按鈕作法

[SQL] 如何快速搜尋整個 SQL Server 資料庫中所有表格所有欄位中的所有資料

[專案] 1/27 開發程式碼留存