【问题标题】:Angular Material Stepper is undefined on first loadAngular Material Stepper 在首次加载时未定义
【发布时间】:2019-10-30 18:17:56
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    使用猫王运算符

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

    在未定义步进器时阻止调用。

    【讨论】:

    • 感谢您的回复,但我的问题是我需要在第一次加载时定义步进器
    • @tayyab_fareed 你的步进器在显示之前不会被定义,你在那里别无选择。您必须将处理推迟到直到加载步进器。在模板中,这是使用 elvis 运算符完成的。如果还是不行,请提供minimal reproducible example或者是不行的TS码。
    【解决方案2】:

    ViewChild 在 vi​​ew init hook 之后获取它的值,但是 angular 尝试在 init hook 之后读取它

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

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

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

    【讨论】:

    • 角5有什么出路吗?
    • 我不这么认为,但为什么你在初始化之后需要这个?在查看初始化挂钩之后,您有什么需要解决的逻辑吗?
    猜你喜欢
    • 2019-12-12
    • 2018-08-08
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2021-05-13
    • 2014-04-14
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多