3

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

2 回答 2

4

使用猫王运算符

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

如果步进器未定义,则阻止调用。

于 2019-06-17T07:23:41.637 回答
3

ViewChild 在查看初始化挂钩后获取它的值,但角度尝试在初始化挂钩后读取它

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

如果您想将项目更新为 Angular 8,您将获得工具来定义何时需要膨胀 ViewChild 变量

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

于 2019-06-17T07:24:04.640 回答