Show angular animation in button click

Issue

I want to trigger animation on button click

  animations: [
  trigger('simpleFadeAnimation', [
  state('in', style({opacity: 1})),
  transition(':enter', [
    style({opacity: 0}),
    animate(300 )
  ]),
  transition(':leave',
    animate(0, style({opacity: 0})))
])
],

Template

  <div class="flex-align h-100"   [@simpleFadeAnimation]>
  <div class="description">{{ screens[currentIndex].title }}</div>
  </div>

Now the animation is showing when the page loads, I want to show fadein animation each time "currentIndex" is changed

Solution

You need to use two animation and switch animation in your component when currentIndex is updated.

I think the example below can help you

@Component({
  ...
  animations: [
    trigger('simpleFadeAnimation', [
      state('hidden', style({
        opacity: 0
      })),
      state('visible', style({
        opacity: 1
      })),
      transition('hidden <=> visible', [
        animate('0.3s ease')
      ])
    ])
  ]
})
export class AppComponent {
  currentState = 'hidden';
  currentIndex = 1;
  nextIndex = null;

  changeCurrentIndex() {
    this.currentState = 'hidden';
    this.nextIndex = 2;
  }

  animationFinished(event: AnimationEvent) {
    if (event.fromState === 'void' && event.toState === 'hidden') {
      this.currentState = 'visible';
    } else if (event.fromState === 'visible' && event.toState === 'hidden') {
      this.currentState = 'visible';
      this.currentIndex = this.nextIndex;
    }
  }
}
<div class="flex-align h-100" [@simpleFadeAnimation]="currentState" (@simpleFadeAnimation.done)="animationFinished($event)">
  <div class="description">{{ screens[currentIndex].title }}</div>
</div>

Answered By – R3tep

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.