首次加载时未定义角材料步进器

时间:2019-06-17 07:20:25

标签: angular angular-material angular5 angular-material-stepper

我正在组件中使用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 

2 个答案:

答案 0 :(得分:1)

使用 Elvis运算符

<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>

如果未定义步进器,则阻止呼叫。

答案 1 :(得分:0)

ViewChild在视图初始化钩子之后获取它的值,但是在尝试在钩子初始化后尝试读取它

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

如果您想将项目更新为角度8,则将获得用于定义何时需要添加ViewChild变量的工具

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