7

I implemented fade in fade out animation for a div element. what I want to do is something like this.

  • when page initial renders there is div element displaying some number.the right and left side i have two-buttons.

  • When a user clicks on one of those buttons I want to remove the numbers in div element and add display the newly created numbers in the div

my problem is when the user clicks on one of those button fade-out part of the animation working fade-in part is not working.

this is stackblitz example

NicoleZ
  • 1,485
  • 3
  • 22
  • 43

2 Answers2

5

It is working as expected. You have two different states that are toggled when you click a button. In initial state, the opacity is 1 and the data is displayed. And in final state the opacity is 0. So the data isn't displayed until you switch to the initial state again.

To achieve your desired behavior, you could use only one state and use :enter and :leave transitions to toggle between the opacity. The following should do it.

Component

import { Component } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
   animations:[
    trigger('fade', [
      state('in', style({ opacity: 1 })),
      transition(':enter', [ style({ opacity: 0 }), animate(600) ]),
      transition(':leave', animate(600, style({ opacity: 0 })))
    ])
  ]
})
export class AppComponent  {
  array = [0, 10, 20, 30, 50]

  goToPrevSet(){
    this.array = this.array.map(data => data - 5)
  }

  goToNextSet(){
    this.array = this.array.map(data => data + 5)
  }
}

Template

<div class="main-container" style="display:inline-flex">
  <button style="padding:5px;font-size:17px;border: 1px solid #1eb2a6; background-color:#d4f8e8;border-radius:5px;cursor: pointer" (click)="goToPrevSet()">Prev</button>
  <div *ngFor="let item of array">
    <div style="padding:5px;" [@fade]="'in'">{{item}}</div>
  </div>
  <button style="padding:5px;font-size:17px;border: 1px solid #1eb2a6; background-color:#d4f8e8;border-radius:5px;cursor: pointer" (click)="goToNextSet()">Next</button>
</div>

Working example: Stackblitz

ruth
  • 29,535
  • 4
  • 30
  • 57
-1

You can do this using following simple step No need to use a function to do a small work which is easily possible with just a 1 line css.

Remove all animation code and comment out changeAnimationState() calling from ts

.animate-opacity{animation:opac 0.8s}@keyframes opac{from{opacity:0} to{opacity:1}}
<div class="animate-opacity" style="padding:5px;">{{item}}</div>