Tuesday, 29 October 2019

Angular CDK: Apply animations to Angular custom stepper on step change

I am stuck with animating the step change of the Angular material custom stepper using the CDK. I have followed the tutorial on how to implement the custom stepper.

I have the demo here

My template looks like:

<section class="container">
 <header>
    <h2>Step /</h2>
    <div>
      <button class="pure-button" cdkStepperPrevious>&larr;</button>
      <button
      class="pure-button"
      *ngFor="let step of steps; let i = index;"
      [ngClass]="{'pure-button-primary': selectedIndex === i}"
      (click)="onClick(i)"
  >
    Step 
      </button>
      <button class="pure-button" cdkStepperNext>&rarr;</button>
     </div>
   </header>

 <div [@stepTransition]="_getAnimationDirection(current)" *ngFor="let step of _steps; let i = index">
  <div  [ngTemplateOutlet]="selected.content"></div>
  </div>

</section>

And my component TS file look like:

import { Component, OnInit } from '@angular/core';
import { CdkStepper } from '@angular/cdk/stepper';
import {
     trigger,
     state,
     style,
     animate,
     transition,
 } from '@angular/animations';

 @Component({
   selector: 'app-my-stepper',
   templateUrl: './my-stepper.component.html',
   styleUrls: ['./my-stepper.component.css'],
   providers: [{ provide: CdkStepper, useExisting: MyStepperComponent }],
  animations: [trigger('stepTransition', [
      state('previous', style({transform: 'translate3d(-100%, 0, 0)', visibility: 'hidden'})),
      state('current', style({transform: 'none', visibility: 'visible'})),
      state('next', style({transform: 'translate3d(100%, 0, 0)', visibility: 'hidden'})),
      transition('* => *', animate('500ms cubic-bezier(0.35, 0, 0.25, 1)'))
   ])]
})
 export class MyStepperComponent extends CdkStepper implements OnInit {
    current = 0;

    onClick(index: number): void {
    this.current = index;
     this.selectedIndex = index;
  }

  ngOnInit() {   
      console.log(this._getFocusIndex())
   }

}

The animation only works for the last step, the reason is that the animation state(previous, current, next)value does not change onClick.

How can I achieve this? any idea is much appreciated, thanks.

UPDATE Check the stackblitz repo for the latest code



from Angular CDK: Apply animations to Angular custom stepper on step change

No comments:

Post a Comment