3

I have the following HTML

<div @fadeInOut *ngIf="state">State is true</div>
<div @fadeInOut *ngIf="!state">State is false</div>

<button (click)="state = !state">Toggle</button>

And I want to animate the :leave and :enter transition. Very trivial I would say

I can do this with the following animation

 trigger("fadeInOut", [
      transition(":enter", [
         style({ opacity: 0 }),
         animate(1000, style({ opacity: 1 }))
      ]),
      transition(":leave", [animate(1000, style({ opacity: 0 }))])
 ])

But the problem is that as soon as the transition begins both elements are visible. What I want is that first the :leave goes away, and then the :enter appears. What is the correct way to achieve this?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

1 Answers1

1

You can achieve it by adding delay for the :enter animation equal to the length of the :leave animation

trigger("fadeInOut", [
  transition(":enter", [
    style({ opacity: 0 }),
    animate("1000ms 1000ms", style({ opacity: 1 }))
  ]),
  transition(":leave", [animate(1000, style({ opacity: 0 }))])
])

Reference: https://angular.io/api/animations/animate

T. Sunil Rao
  • 1,167
  • 5
  • 14
  • This is what I've tried, it seems that the delay does not influence the insertion of the entering element, but only when the animation starts: [stackblitz](https://stackblitz.com/edit/angular-ivy-uyoiln?file=src%2Fapp%2Fapp.component.ts) – Jeanluca Scaljeri Feb 16 '21 at 20:20
  • Animation is working as you wanted. Your problem is to show only one element at a time. It can achieved by putting the divs in a container and hiding the overflow. – T. Sunil Rao Feb 16 '21 at 20:31
  • Yes I see what you mean. If I give the button a position absolute (it will not jump up-and-down) but that does not fix it completely. I would expect that it was possible to delay the insertion of that :entering element – Jeanluca Scaljeri Feb 16 '21 at 20:42
  • Did you have something like this in mind: [stackblitz](https://stackblitz.com/edit/angular-ivy-kxcqva?file=src%2Fapp%2Fapp.component.ts)? I don't like this, I hoped that angular was able to do this for me – Jeanluca Scaljeri Feb 16 '21 at 20:52
  • 1
    The problem is in the order of the elements. I have sorted it out making position absolute and background transparent. Check https://stackblitz.com/edit/angular-ivy-p5dj2y. It would work best in router-outlet as leaving element will always be first and entering element will always be next. – T. Sunil Rao Feb 16 '21 at 21:05