Search code examples
angularjstypescriptwebpackng-animate

ngAnimate with Angular 1.4 + TypeScript not working during page load


TL;DR

View is fading in at the beginning when using ES5 (ES5 Example)

View does NOT fade in when using Typescript import (Typescript and ES6 Import Example)


I am currently experimenting with Typescript, ES6 modules and how to integrate all those technologies. In most cases everything works finde. However, I'd like to animate the ui-view with ngAnimate and here comes the problem. Somehow, if I am using ES6 modules and its import statement, it seems that my dependencies are lazy loaded, so that ngAnimate will not work during the initial page load. Once the page has been loaded, the animation works just fine, e.g. animating the view in and out if the user clicks on a link. What I'd like to see is that the ui-view fades in at the beginning.

I have set up two Plunker to demonstrate both the behaviour with an app in plain old ES5 and a Typescript one, that uses SystemJS and the import statement to load its dependencies.

Here is the ES5 example. If you run this Plunker you will notice how the view fades in at the beginning. All I did was including the files via script tag in the index.html. The animation is done via plain CSS:

ui-view.ng-enter {
  animation: fadeIn .5s ease both;
  animation-delay: .3s;
}

ui-view.ng-leave {
  animation: fadeOut .5s ease both;
}

Here is the Typescript example. You will hopefully see the difference, that the view will not fade in even though it uses the same animation mechanism. The only difference here is that I am using Typescript (shouldn't be the problem) and ES6 modules which get imported via import. It somehow seems that if I am using import ngAnimate is not fully loaded or maybe not even loaded at all at the time the page loads up. Maybe it's lazy loaded?

I'd really like to get this stack working, because it is so much more fun and modern. Any ideas?


Solution

  • After some investigation and the help of one of the Angular team members I found out that ngAnimate disables all animations on load for the first two digest by default. This means if it detects any remote assets being downloaded then it keeps waiting until they are ready. This is somehow the case when you are using Typescript / ES6 modules. You can work around this situation and guarantee that all animations run on bootstrap even though remote assets are being downloaded by creating a directive to enable animations with $animate.enabled(true);. You can either place the directive on the body or html tag. In the Plunker above I have added the directive to the body tag. This is what you need:

    <body allow-animations-on-load>
      <ui-view></ui-view>
    </body>
    
    app.directive('allowAnimationsOnLoad', ['$animate', function($animate) {
      $animate.enabled(true);
    }]);
    

    I have also updated the corresponding Plunker. As you can see the animation is now fading in on bootstrap.