Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material selectionChanged returning previous step instead of current

I have a page consisting of two columns. One contains a vertical stepper and the other one should contain a description for each step. I want to update this description according to the current step and therefore listen to the selectionChange-Event. The problem is, that I get the previously chosen step when I look for the selectedIndex, not the one I am now on.

HTML:

<div class="row"> <div class="col-7 stepperColumn"> <mat-vertical-stepper (selectionChange)="onStepChange(eventCreationStepper)" #eventCreationStepper> <!--some steps--> </mat-vertical-stepper> </div> <div class="col-5"> <!--some descriptions--> </div> </div>

JS:

public onStepChange(stepper: MatStepper) { console.log(stepper.selectedIndex); }

like image 962
Rustius Avatar asked Apr 13 '18 12:04

Rustius


People also ask

What is stepControl in Mat stepper?

For each mat-step , the stepControl attribute can be set to the top level AbstractControl that is used to check the validity of the step. There are two possible approaches. One is using a single form for stepper, and the other is using a different form for each step.

How do I get my mat stepper index?

Steps to reproduce: Create a mat-stepper component that renders mat-step elements from an array. Pass in the selected index from the component (initially set to 0) Add a new element to the steps array for a dynamically added step and set the selected index to the new step index.

How to use selection change in angular?

The event selectionChange is used with <mat-select> element as following. Our function onBookChange() will execute every time when there is selection change. To get the selected value we can pass $event to the function. We can also get selected value using FormControl , FormGroup and NgModel .


1 Answers

At first this seems like odd behaviour, but after thinking about it I realise it's because you're passing through the template ref before you've changed the step, so the object that arrives in your method is still pointing at the previous step.

It looks like the solution is to grab the new index from the event object that is passed by the selectionChange method, like this:

HTML:

<mat-vertical-stepper (selectionChange)="onStepChange($event)">

TS:

public onStepChange(event: any): void {
  console.log(event.selectedIndex);
}

This should solve your problem.

like image 77
lordchancellor Avatar answered Nov 06 '22 23:11

lordchancellor