Fade out animation when ng-if = false

Is there any way to animate with fade out when ng-if="false" instead of instantly hide the HTML element?

I can fade-in when ng-if="true" but can't when ng-if="false". When ng-if="true" I'm using Animate.css library to animate with fade-in.

Upvotes: 15

Views: 17936

Answers (1)

Samantha Adrichem
Samantha Adrichem

Reputation: 862

You should use ng-animate for this. It's a native angular library that adds transition classes and a delay upon removing elements

angular.module('app', ['ngAnimate']).
controller('ctrl', function(){});
.fade-element-in.ng-enter {
  transition: 0.8s linear all;
  opacity: 0;
}

.fade-element-in-init .fade-element-in.ng-enter {
  opacity: 1;
}

.fade-element-in.ng-enter.ng-enter-active {
  opacity: 1;
}

.fade-element-in.ng-leave {
  transition: 0.3s linear all;
  opacity: 1;
}
.fade-element-in.ng-leave.ng-leave-active {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <a href="" ng-click="showMe = !showMe">Click me</a>
  <div class="fade-element-in" ng-if="showMe">
    SomeContent
  </div>
  <div class="fade-element-in" ng-if="!showMe">
    SomeOtherContent
  </div>
</div>

Upvotes: 30

Related Questions