Search code examples
angularangular-animations

how to dynamically set the number of states in angular


  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('slide', [
      state('1', style({ transform: 'translateX(0)' })),
      state('2', style({ transform: 'translateX(-50%)' })),
      transition('* => *', animate(300))
    ])
  ]
})

export class SlidePanelComponent {
  @Input() numberOfStatesToHave

... more code

How can I dynamically set the number of states in angular using the @input decorator?

For example if the @Input numberOfStatesToHave is 3, how can I have three animations states in the animations 'array' in the @Component decorator? And also dynamically pass values to the transform css property?


Solution

  • After doing research(thanks to @SplitterAlex comment that pointed me to the right direction), I have come up with a solution.

    To dynamically create animation states you should have the animations logic inside the @Components decorator but rather you should use angular's Animationbuilder.

    This stackblitz example helped me understand how the animation builder works as it contrasts it with doing the animation inside the @Component decorator.

    Here is my complete code of dynamically setting the number of animation states in angular.