0

I'm creating an animation in angular, I need to know when it starts so I defined a callback. The thing is the callback is triggered when the component loads, even without changing the state.

Template

<button (click)="click()">click</button>
<div class="myclass" [@throwBall]="state" (@throwBall.start)="animStart($event)" >  
</div>  

The component:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    trigger('throwBall', [
      state('steady', style({ })),
      state('throw', style({ top: '300px' })),
      transition('steady => throw', [animate('2s')])
    ]),
    trigger('blockInitialRenderAnimation', [
        transition(':enter', [])
    ])
  ]
})
export class AppComponent  {
  state = 'steady';

  click() {
    this.state = 'throw';
  }
  animStart(event: any) {
    if (event.fromState !== 'void') {
      console.log('anim start callback');
    }
  }
}

Here is a demo: https://stackblitz.com/edit/angular-9szgic

Why is the 'anim start callback' being displayed in the console when the component loads?

Community
  • 1
  • 1
Bonomi
  • 2,541
  • 5
  • 39
  • 51

1 Answers1

0

The initial state of animation is a "stateless" state called void - which is the default state when using animations. After initializing your state variable to steady a non-existing animation is starting from void -> steady.

In order to reach your goal, you should use properties fromState & toState of AnimationEvent.

import { AnimationEvent, } from '@angular/animations';

public animStart(event: AnimationEvent): void {
   if(event.fromState === 'steady') {
      // ...
   }
}

Try to log AnimationEvent in your animStart method in order to better understand this interface.

public animStart(event: AnimationEvent): void {
   console.log(event);
}
Ron Rofe
  • 738
  • 1
  • 9
  • 25
  • I took that approach but seems a bit dirty. Why is the callback called if there was no animation triggered? At least I haven't defined anything from void to 'steady'! – Bonomi May 06 '20 at 08:16
  • 1
    @Bonomi It fires an event for every transition that occures, so `void => 'steady'` also triggers a callback, even though you may not have defined an animation for it. –  May 06 '20 at 08:39
  • This is how Angular built my friend. VOID is very useful if you want to initiate some animation when the component is loaded. Just like we have "ngOnInit()". – Ron Rofe May 06 '20 at 09:41