![]()
What You’ll Learn
How to integrate CSS3 animations into AngularJS
Using ngAnimate for smooth transitions
Applying ng-enter and ng-leave for dynamic effects
Best practices for performance optimization
1️⃣ Setting Up AngularJS with ngAnimate
To enable animations, include AngularJS and ngAnimate in your project.
Step 1: Include AngularJS & ngAnimate
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-animate.min.js"></script>
Step 2: Define the AngularJS App
var app = angular.module('myApp', ['ngAnimate']);
2️⃣ Creating CSS3 Animations
We will use CSS3 animations to create fade-in and fade-out effects.
CSS Code
/* Fade-in effect */
.fade-animation.ng-enter {
opacity: 0;
transition: opacity 0.5s ease-in;
}
.fade-animation.ng-enter-active {
opacity: 1;
}
/* Fade-out effect */
.fade-animation.ng-leave {
opacity: 1;
transition: opacity 0.5s ease-out;
}
.fade-animation.ng-leave-active {
opacity: 0;
}
3️⃣ Applying CSS3 Animations in AngularJS
We will apply the fade effect when adding/removing an element.
HTML Code
<div ng-app="myApp" ng-controller="MainCtrl">
<button ng-click="toggleMessage()">Toggle Message</button>
<div class="fade-animation" ng-if="showMessage">
<p>Hello! This is a fade-in/fade-out animation.</p>
</div>
</div>
JavaScript Code
app.controller('MainCtrl', function ($scope) {
$scope.showMessage = false;
$scope.toggleMessage = function () {
$scope.showMessage = !$scope.showMessage;
};
});
How It Works?
✔ Clicking the button adds/removes the <p> element.
✔ ng-if triggers ng-enter (fade-in) when the element appears.
✔ ng-leave (fade-out) applies when the element disappears.
4️⃣ More CSS3 Animations with AngularJS
You can also create slide-in/slide-out effects!
Slide Animation (CSS)
/* Slide-in effect */
.slide-animation.ng-enter {
transform: translateX(-100%);
transition: transform 0.5s ease-in-out;
}
.slide-animation.ng-enter-active {
transform: translateX(0);
}
/* Slide-out effect */
.slide-animation.ng-leave {
transform: translateX(0);
transition: transform 0.5s ease-in-out;
}
.slide-animation.ng-leave-active {
transform: translateX(-100%);
}
Updated HTML Code
<div class="slide-animation" ng-if="showMessage">
<p>Slide-in and Slide-out Animation!</p>
</div>
Optimizing Performance
Use ng-if instead of ng-show – This removes the element from the DOM instead of just hiding it.
Use will-change property in CSS for better rendering.
Use hardware-accelerated animations (transform instead of left/right).
