javascriptcssangulartypescriptangular-animations

Configuring an Angular Animation with component input parameters?


I'd like to be able to provide an @Input parameter for the timing of the animation in this circle progress demo.

However the animation is configured inside the @Component decorator and if I understand correctly that code does not have access to the components runtime state.

@Component({
  selector: 'el-circle-progress',
  standalone: true,
  imports: [CommonModule],
  templateUrl: `./svg-circle.component.svg`,
  styleUrls: ['./svg-circle.component.css'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('animateStroke', [
      state(
        '*',
        style({
          'stroke-dashoffset': '*',
        })
      ),
      transition('*<=>*', animate('3s linear')),
    ]),
  ],
})

Is there a way to configure dynamic animation parameters?

Currently the transition is configured like this:

transition('*<=>*', animate('3s linear')),

And I'd like to make the 3s dynamic ...


Solution

  • Was playing around a bit in your stackblitz, and modified it to be as so: https://stackblitz.com/edit/stackblitz-starters-e2xenn?file=src%2Fsvg-circle.component.svg

    Thanks goes to this medium article: https://medium.com/@danieltamirr/parameterized-angular-animations-fa73a2727158

    In a nut shell we define a parameter value for our animation in our templat:

    [@animateStroke]="{ value: dashOffset, params: {timer: '1s linear'}}"

    Then inside of the actual component definition we can reference it as so:

    style({
              'transition': '{{timer}}',
              'stroke-dashoffset': '*',
    
            }), { params: {timer: '1s linear'}}
    

    Whereby the param value is just a default in case it is not provided from the template itself. Thus if say your template just had this for animate stroke:

    [@animateStroke]="dashOffset"

    it would then default to an animation speed of 1s linear, or whatever it is you want to define in that template