2

I have a custom stepper based on Cdk, but it is dynamic. So it is bound to a FormArray. When a item is added to the formArray I need to redirect to the newest step. CdkStepper doesn't seem to trigger any event on item being added to step collection.

I've tried to subscribe to the valueChange on the FormArray but it triggers before a new step is added.

Here is a stackblitz with a setup.

Ingó Vals
  • 4,788
  • 14
  • 65
  • 113

1 Answers1

3

CdkStepper has a _steps: QueryList<CdkStep> property which has a changes: Observable<any> property that emits values as new steps added into CdkStepper.

However, when used on OnInit _steps property seems to be not populated yet. So using a settimeout to wait for next changedetection cycle for _steps to get initialized solves the problem. In your example, change CustomStepperComponent as follows:

ngOnInit() {
  setTimeout(()=>{
    this._steps.changes.subscribe(x => {
      this.selectedIndex = x.length - 1;
    });
  });
}

here is my working demo

https://stackblitz.com/edit/angular-cdkstepper-formarray-jnftgb

btw, _steps property is deprecated in "@angular/material": "8.0.0"

ysf
  • 4,634
  • 3
  • 27
  • 29
  • 1
    _steps was replaced in v7 with the getter steps to better encapsulate the field. So the field isn't going away just may get hidden eventually and you should just start using steps instead of _steps to do the same things. Should be an easy change to make. – Rodney S. Foley Jul 22 '19 at 19:40
  • Hi ysf and @Ingó Vals. I know this question has aged a little but does anyone of you have an exmaple of a working TestBed setup for this kind of Custom Stepper? The implementation was really smooth but the test setup is nowhere described. Mocking the steps seems to be a crutial part that is just eluding me.. If one of you has a sample setup i will gladly post this as a new question for the sweet rep gain. – Berlin_Bro Feb 11 '20 at 12:38
  • @Berlin_Bro I am afraid I don't have such TestBed setup. but feel free to post it as a question anyway. – ysf Feb 21 '20 at 06:56