Search code examples
angularangular-cdkformarrayangular-material-stepper

Angular Cdk stepper, how to detect when new step added


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.


Solution

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