Home > Software engineering >  Show angular animation in button click
Show angular animation in button click

Time:04-20

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    [@simpleFadeAnimation]>
  <div >{{ 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

CodePudding user response:

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  [@simpleFadeAnimation]="currentState" (@simpleFadeAnimation.done)="animationFinished($event)">
  <div >{{ screens[currentIndex].title }}</div>
</div>
  • Related