0
votes

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.

1
:enter and :leave are just aliases for void => * and * => void, there is no difference - Mike S.

1 Answers

2
votes

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.