0

I'm trying to understand animations in angular but I'm having a really hard time with it at the moment. Any learning sources would be appreciated besides this concrete example.

Here is the stackblitz.

My goal is to animate a component every time it is created and destroyed via *ngIf condition.

Current Problems:

  • where animation is applied to the parent animation works only on first load (that's the only time it does work)
  • animation that is applied to children causes weird glitch: it clones a component for a period of time (obviously less then I have entered anywhere) instead of destroying current component and recreating it after 1 second

I hope it's not too complicated to look at. I created 4 examples so I could figure out what's the difference between using :enter + :leave as opposed to void => * + * => void, and to whom do they really apply: child or the element itself?

Striked issues are answered.

ucimo
  • 105
  • 11
  • 2
    `:enter` and `:leave` are just aliases for `void => *` and `* => void`, there is no difference –  Apr 28 '20 at 07:58

1 Answers1

2

Animations always apply to the element that they are bound to.

<div @comeOrGo>
    <hello *ngIf="show11" [name]="'Animation (1.1 on parent)'"></hello>
</div>

The reason why this works initially is that the div is created and animated into view by angular.

However when you toggle it via the button, merely the hello component is removed from DOM, but not the div (which the animation is bound to).

To fix we can do this:

  <div @comeOrGo *ngIf="show11">
        <hello [name]="'Animation (1.1 on parent)'"></hello>
    </div>

This removes the div from DOM (and also hello) and therefore triggers animation.

As for the duplication glitch when you toggle the buttons to quickly:

The Problem with this is that when Angular removes an element from DOM and that element has an animation, it will always play this animation, even if it creates the component again afterwards.

I don't know the best solution for it, but if the user is allowed to rapidly click the toggle button, you shouldn't be using a :leave animation anyway.

  • Thank you, that was really helpful. So basically I should always put these animations on the container of the element I want to animate in and out of existence? – ucimo Apr 28 '20 at 08:36
  • 1
    It depends on what you're trying to do, if there is more than one element inside the `div` that you're removing using `*ngIf`, all child components will be destroyed aswell. If you only wanted to remove `hello`, but not the `div`, you'd have to place the animation on `hello` instead. –  Apr 28 '20 at 08:45
  • So corrected my [stackblitz](https://stackblitz.com/edit/understanding-angular2-animations?file=src%2Fapp%2Fapp.component.html) in order try and get a bit more specific answer regarding what you said about putting animation on each `hello` I want to animate. How would I accomplish that? – ucimo Apr 28 '20 at 18:15