簡體   English   中英

首次加載時未定義角材料步進器

[英]Angular Material Stepper is undefined on first load

我在組件中使用Angular Material Stepper。 問題是,第一次加載組件時,它會因錯誤消息而中斷

ERROR TypeError: Cannot read property 'selectedIndex' of undefined

我的范本

<mat-horizontal-stepper #stepper>
        <!-- Steps -->
</mat-horizontal-stepper>    
<div>
    <button (click)="goBack(stepper)" type="button" 
        [disabled]="stepper.selectedIndex === 0">Back</button>
    <button (click)="goForward(stepper)" type="button" 
        [disabled]="stepper.selectedIndex === stepper._steps.length-1">Next</button>
</div

我的TS

import { MatStepper } from '@angular/material/stepper';

goBack(stepper: MatStepper){
    stepper.previous();
}

goForward(stepper: MatStepper){
    stepper.next();
}

我也將TS中的步進定義為

@ViewChild('stepper') stepper: MatStepper;

但是,如果我將[disabled]屬性用作

<div>
    <button (click)="goBack(stepper)" type="button" 
        [disabled]="stepper ? stepper.selectedIndex === 0 : false">Back</button>
    <button (click)="goForward(stepper)" type="button" 
        [disabled]="stepper ? stepper.selectedIndex === stepper._steps.length-1 : false">Next</button>
</div

比步進器工作正常。

注意:

Angular Version is :5.2.8
Angular Material Version:5.2.5 

使用貓王運算符

<button (click)="goBack(stepper)" type="button" 
    [disabled]="stepper?.selectedIndex === 0">Back</button>

相當於

<button (click)="goBack(stepper)" type="button" 
    [disabled]="stepper ? stepper.selectedIndex === 0 : false">Back</button>

但是更干凈。 對於點擊事件,您可以執行此操作

<button (click)="stepper && goBack(stepper)" type="button" 
    [disabled]="stepper?.selectedIndex === 0">Back</button>

如果步進器未定義,則阻止呼叫。

ViewChild在查看init鈎子之后獲取它的值,但是在init鈎子后嘗試嘗試讀取它的值

https://angular.io/guide/lifecycle-hooks

如果您想將項目更新為angular 8,則可以使用工具定義何時需要添加ViewChild變量

https://v8.angular.io/guide/static-query-migration

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM