Search code examples
angularanimationangular-animations

How do you repeat an animation on click in angular?


new to angular animations here... I want to repeat a simple fade in animation on button click for two images. Each time the button is clicked, I want the old images to fade out and new images to fade in. Currently, after first click, images fade in. After second click, images fade out. I would like fade out and in to happen every click.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [  
  trigger('fade', [
    state('startRound', style({opacity:1})),
    state('endRound', style({opacity:0})),
    transition('* <=> *',[
      animate(500)
    ])
  ])
]
})
export class AppComponent  {
  
  public state:string = 'endRound';

  changeState(){
      this.state = this.state == 'startRound' ? 'endRound' : 'startRound';     
  }

  onClick(){
  this.changeState();
  }

}
<p>
  <img src="https://media.istockphoto.com/vectors/football-grunge-background-vector-id985653890" [@fade]=state>
  <img src="https://media.istockphoto.com/vectors/football-grunge-background-vector-id985653890" [@fade]=state>
</p>
<button (click)="onClick()">Click Me</button>

https://stackblitz.com/edit/angular-ivy-fzpmwm?file=src/app/app.component.ts

Thanks


Solution

  • it's better your state variable to be a boolean

    animations: [  
      trigger('fade', [
        state('false', style({opacity:1})),
        state('true', style({opacity:0})),
        transition('* <=> *',[
          animate(500)
        ])
      ])
    
     ...
     public state:boolean = false;
    
     changeState(){
        this.state = !this.state
     }
    

    So you can write [@fade]="state" and [@fade]="!state", else you need use two variables

    <img src="..." [@fade]="state">
    <img src="..." [@fade]="!state">
    

    Your forked stackblitz

    Update if we want we can use tiggers, that,e.g. if our images are

    <img src="..." [@fade]="state" (@fade.done)="state && state=!state">
    <img src="..." [@fade]="state">
    

    At first our state is false (opacity=1), when click state becomes true, so make the animation to get (opacity=0), after finished the animation, as state is true, execute state=!state and animation beging to get (opacity=1), after finished this last animation, states is false and don't repeat the animation

    I updated the stackblitz