hullunist
hullunist

Reputation: 1277

Angular Animations: How to set transition timing dynamically?

I'm currently implementing Animations in an application and I face the problem that the timings for animation transitiions are stored in a json config file (I can't change that). There is a service that provides the values needed but since Angular Animations are declared in the @Component block I am not able to access the service.

transition('start => end', [animate(ConfigService.config.delay.firstDelay)])

This results as expected in an undefined error. I saw that one can build animations using the AnimationBuilder but it seems doing that way only provides the opportunity to provide simple animations without specific callbacks and multiple state transitions.

What would be the best approach to implement the transition timing in a dynamic way?

Upvotes: 0

Views: 1270

Answers (1)

Eliseo
Eliseo

Reputation: 57939

you can use "manual Animations". the "translation" from a typical animation and a manual animation it's not difficult

In your component you defined

import {style,animate,AnimationBuilder,AnimationFactory,AnimationPlayer} from "@angular/animations";

 private player: AnimationPlayer;
 constructor(private builder: AnimationBuilder) {}

And create a function that "anime" an element, e.g.

/*I want "recreate" the animation
 transition(':enter', [
    style({ opacity: 0 }),
    animate('100ms', style({ opacity: 1 })),
  ]),
  transition(':leave', [
    animate('100ms', style({ opacity: 0 }))
  ])
*/
animate(element: any, state:string) {
    const myAnimation = state=='enter'?
       this.builder.build([
          style({ opacity: 0 }),
          animate(this.timing, style({ opacity: 1 }))
       ]):
       this.builder.build([
        animate(this.timing, style({ opacity: 0 }))
     ])
     ;
    this.player = myAnimation.create(element);
    //you can control when the animation is finish
    this.player.onDone(()=>{
        this.toogle=!this.toogle;
    })
    this.player.play();
  }

So You can has, e.g.

<div #div style="background-color:red;width:5rem;height:5rem"></div>
<button (click)="animate(div,toogle?'enter':'leave');">click</button>

Or using ViewChild get an element and make the animation or call in ngOnInit or...

Upvotes: 1

Related Questions