Search code examples
angularangular-animations

How to use Angular animations sequence() method to trigger animation only after one finishes?


I have two elements on the page that I want to animate sequentially.

1. h1 tag
2. the background image

My component's html template looks like this:

`<div class="container">
  <h1 [@flyInOut]="isIn ? 'in' : 'out'"  class="welcome-title">WELCOME</h1>
</div>
<div [@flyInOut]="isIn ? 'in' : 'out'"  class="background">  <div class="gradient">
    <div class="container">
        <div style="height: 350px;"></div>        
    </div>    
  </div>
</div>`

I have the following animation:

`animations: [
    trigger('flyInOut', [
      state('in', style({ transform: 'translateX(0)'})),
      transition(':enter', [
        style({
          transform: 'translateY(-3%)',
          opacity: 0,
          position: 'static'
        }),
        sequence([          
          animate(
            '3.5s ease-in-out',
            keyframes([
              style({ transform: 'translateY(50%)', opacity: 0 }),
              style({ transform: 'translateY(0%)', opacity: 1 }),
            ])
          ),
          animate('2.5s .2s ease-in', keyframes([
            style({ opacity: .0, offset: .2 }),
            style({ opacity: .2, offset: .6 }),
            style({ opacity: .4, offset: .8 }),
            style({ opacity: .99, offset: 1 })
          ]))
        ])  
      ])
    ]),`

All I am looking to do is simply run the first animate function, only THEN run the second animate function. According to angular docs, I should be able to accomplish this with the sequence method, but this is not the case.

What I am seeing is that the given code, will execute both animations in parallel and once it has finished doing the first animation it will then trigger the second animation.

I have a feeling its something with how I am using the animations in the HTML template. Any recommendations?


Solution

  • You can use Animation callbacks.

    Just add in your h1 tag

    <h1 [@flyInOut]="isIn ? 'in' : 'out'" (@flyInOut.done)="animationDone($event)" class="welcome-title">WELCOME</h1>

    and for div use new flag, e.g.:

    <div [@flyInOut]="isDivIn ? 'in' : 'out'" class="background"> <div class="gradient">

    which you can set to true in animationDone function:

    animationDone(event: AnimationEvent) { this.isDivIn = true; //or false, depends on your specific logic }

    so, as soon as h1 animation is done, your flag(isDivIn) will be set as true and div animation begin.