javascriptcssangularjsng-animateng-show

How to smoothly show a block with background and text with Angular and ngAnimate?


I'm new in JS and Angular. I try to make ng-show and ng-hide for my background and text. The problem is with my text: I can hide it smoothly, but when it's shown - I get all text first and just then I get my backround. How can I fix it?

JS:

var app = angular.module('myApp', ['ngAnimate']);

CSS:

div {
    overflow: visible;
    transition: all linear 0.5s;
    background-color: lightblue;
    height: 100px;
}

.ng-hide {
    overflow: hidden;
    height: 0;
opacity: 0;
}

HTML:

<input type="checkbox" ng-model="myCheck"/>

<div ng-show="myCheck">
    Many text here<br/>
    Many text here<br/>
    Many text here<br/>
    Many text here<br/>
    Many text here<br/>
    Many text here<br/>
</div>

Solution

  • You can specify a class for your div and use ng-hide transitions to control the animation.

    Here is a simple demo:

    var app = angular.module('myApp', ['ngAnimate']);
    app.controller('myCtrl', function($scope) {
      $scope.myCheck = false;
    });
    .myClass {
      overflow: visible;
      background-color: lightblue;
      height: auto;
      transition: all 0.5s ease-in-out;
      transform: translateY(0);
    }
    
    .myClass.ng-hide {
      transform: translateY(-100%);
    }
    
    .myClass.ng-hide-remove,
    .myClass.ng-hide-add.ng-hide-add-active {
      opacity: 0;
    }
    
    .myClass.ng-hide-add,
    .myClass.ng-hide-remove.ng-hide-remove-active {
      opacity: 1;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-animate.js"></script>
    
    <div ng-app="myApp" ng-controller="myCtrl">
    
      <input type="checkbox" ng-model="myCheck" />
      <span>{{myCheck?'Hide':'Show'}}</span>
    
      <div class="myClass" ng-show="myCheck">
        Many text here<br/> Many text here<br/> Many text here<br/> Many text here<br/> Many text here<br/> Many text here<br/>
      </div>
    
    </div>