javascriptangulartypescriptanimationangular-animations

Creating an Angular Animation that can use an @Input() value?


Is it possible to create an Angular Animation with custom parameters passed in via a function, and then using the resulting animation within a component?

For example in this demo the animation is created in a separate animations.ts like this:

import {
  trigger,
  state,
  style,
  transition,
  animate,
  group,
} from '@angular/animations';

export const SlideInOutAnimation = [
  trigger('slideInOut', [
    state(
      'in',
      style({
        width: '50%',
        opacity: '1',
        visibility: 'visible',
      })
    ),
    state(
      'out',
      style({
        width: '50px',
        opacity: 0.3,
        visibility: 'visible',
      })
    ),
    transition('in => out', [
      group([
        animate(
          '600ms ease-in-out',
          style({
            width: '50px',
          })
        ),
      ]),
    ]),
    transition('out => in', [
      group([
        animate(
          '1ms ease-in-out',
          style({
            visibility: 'visible',
          })
        ),
        animate(
          '600ms ease-in-out',
          style({
            width: '50%',
          })
        ),
        animate(
          '800ms ease-in-out',
          style({
            opacity: '1',
          })
        ),
      ]),
    ]),
  ]),
];

And this animation can then be imported an used in a component that declares the animation in the animations property of the @Component decorator.

But what if we want to take an @Input property value and pass that to the animation.

For example if we have something like:

@Input()
width: 50%;

How would we pass this parameter to the animation?


Solution

  • Animations with "parameters" are not so difficult.

    Imagine something simple.

    animations:[
        trigger('custom',[
          transition('*=>*', [
            style({ width: `{{width}}`  }),
            animate('500ms ease-in', style({ width: `100%`  })),
          ],{params:{ width: "0"}}),
        ])
     ]
    

    We include the "parameters" in the "params" (that it's an object) and when we want to use it's enclosed by {{ }}.

    It's necessary to indicate a params by defect.

    Then only, when define the animation in the .html is pass the parameters, e.g. if you have two variables "value" and "width" you can have a html like

    <div class="header" [@custom]="{value:value,params:{width:width}}" >
    

    Then, when we change the "value" the animation begins

    <button (click)="width='50%';value=!value">width:50%</button>
    <button (click)="width='0';value=!value">width:0</button>
    

    See stackblitz

    In the Stackblitz I use a variable in the component, but you can use an Input, but remember that if you want animation begings you need change the "value" (unless you use :enter and :leave)