I'm using Angular Material Stepper in a component. The problem is that when the component loads for the first time it breaks with the error message
ERROR TypeError: Cannot read property 'selectedIndex' of undefined
My Template
<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
My TS
import { MatStepper } from '@angular/material/stepper';
goBack(stepper: MatStepper){
stepper.previous();
}
goForward(stepper: MatStepper){
stepper.next();
}
And I also have stepper defined in TS as
@ViewChild('stepper') stepper: MatStepper;
But if I use the [disabled] property as
<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
than the stepper works as expected.
Note:
Angular Version is :5.2.8
Angular Material Version:5.2.5
Use the Elvis operator :
<button (click)="goBack(stepper)" type="button"
[disabled]="stepper?.selectedIndex === 0">Back</button>
It's the equivalent of
<button (click)="goBack(stepper)" type="button"
[disabled]="stepper ? stepper.selectedIndex === 0 : false">Back</button>
But cleaner. For the click event, you can do this
<button (click)="stepper && goBack(stepper)" type="button"
[disabled]="stepper?.selectedIndex === 0">Back</button>
To prevent the call if the stepper is undefined.
ViewChild gets it's value after view init hook, but angular try to read it after init hook
https://angular.io/guide/lifecycle-hooks
if you'd like to update your project to angular 8, you'll get tools to define when you need to inflate ViewChild variable
https://v8.angular.io/guide/static-query-migration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With