When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf.

The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution.

1) When the current element begins its exit animation, it is still present in the DOM.

2) The new element starts its animation during this overlap.

3) The main problem arises when the exiting element completes its animation and is removed from the DOM while the entering element is already visible, resulting in a UI glitch.

The code snippet below, though not written by me, reflects my dilemma.

Could someone provide guidance on how to resolve this issue?

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>

Answer №1

When dealing with one item at a time, it's best to utilize the position: absolute property to prevent any interference with each other's positioning.

For additional enhancements, consider implementing the ng-class directive for adding animations.

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.5s linear all;
  opacity: 1;
}

.fade-element-in.ng-leave.ng-leave-active {
  opacity: 0;
}

.container {
  position: absolute;
}
<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="container">
    <div ng-class="{'fade-element-in': showMe}" ng-if="showMe">
      SomeContent
    </div>
  </div>
  <div class="container">
    <div ng-class="{'fade-element-in': !showMe}" ng-if="!showMe">
      SomeOtherContent
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Javascript Date and Time Validation

My application includes code that is supposed to display HTML pages based on today's date and the time of day (morning, afternoon, or evening). However, it seems like there is an issue with how the time is being checked. Currently, at 2:53pm, only the ...

What is the best way to add a border around an image along with a button using VueJS?

I am struggling to link a button and an image in VueJS to display a border around the picture. While I can successfully display the border on the button, I am unsure how to extend it to the image as well. Vue.component('my-button', 'my-img& ...

Coloring a table in vue.js based on performance rankings

I'm facing an issue with sorting my data performance in vue js. Here is the script I have created so far: <template> <div> <div class="row"> <h2> Campaign Performance </h2> <table class=&q ...

What is preventing me from assigning all padding values at once?

I attempted to modify all paddings of the html element using JavaScript, with the following code: const pd = 1 document.getElementsByClassName('board')[0].style.paddingRight = pd + 'px' document.getElementsByClassName('board') ...

Refresh the datatable using updated aaData

How do I automatically update the Datatable with new Json data? POST request is used to receive data, which is then sent to the LoadTable function in order to populate the datatable. function initializeTable(){ $("#submitbutton").on( 'click', ...

Why does the browser keep converting my single quotation marks to double, causing issues with my JSON in the data attribute?

This task should be straightforward, but I seem to be facing a roadblock. I am trying to insert some JSON data into an input's data attribute, but the quotes in the first key are causing issues by prematurely closing the attribute. Here is the code ...

My element is not being animated by Elementbyclass

Without Using JQUERY The animation I'm trying to create isn't functioning properly. I attempted to utilize document.getElementsByClassName, but it's not working as expected. There are no errors, but the element is not animating correctly. ...

Determining the elapsed time using Momentjs

I need assistance with a NodeJS project where I am trying to determine if a specific amount of time (like 1 hour) has passed since creating an object. My project involves the use of MomentJS. For example, if moment(book.createdAt).fromNow() shows 2 hours ...

Tips for locating a key within an object that houses a specific value in its array

In my Coffeescript code, I have created the following Javascript object: urlSets = a: [ 'url-a.com' 'url-b.com' 'url-c.com' ] b: [ 'url-d.com' 'url-e.com' 'url-f.com&a ...

A function cannot be used with Random Song Loop

Recently delving into the world of JavaScript, I encountered a peculiar issue. When attempting to execute the following code within a function, nothing displays in the console. Yet, after testing it without the function, the expected strings appear as inte ...

Verify if the button is assigned a specific class, then generate a 'completed' div

I'm new to working with Jquery and I have a question. In my upload form, when something is uploaded the upload-button changes class from: <a class="upload-button upload buy" id="upload-button"><span>Upload a document</span></a> ...

Initiating a YouTube video with a click on its thumbnail image - a jQuery tutorial

I am currently working on code that successfully displays YouTube videos. However, I would like the video to start playing when the cover image is clicked. How can I achieve this functionality? Thank you for your help! <div id="video" style="display: ...

Problems with Ajax calls are preventing Internet Explorer9 and Internet Explorer10 from functioning properly

I am facing an issue with displaying item pages using Ajax. The function works perfectly in Chrome, but not in Internet Explorer. <script type="text/javascript"> function obtainInfo(str) { if (str=="") { document. ...

How to exclude elements nested inside another element using CSS or XPath techniques

Presented here is a snippet of XML code: <xml> <section> <element>good</element> <section class="ignored"> <element>bad</element> </section> </section> </xml> Identifying a ...

Unable to retrieve data from the $.getJSON method

Using $.getJSON in jQuery, I am retrieving the necessary data from the server. Below is an example of how it is structured: $.getJSON("/dataParser/parseVoltage",function(jsondata, status) { if (status == "error") { console.log("Error occurred whil ...

Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number: const array: boolean[] = [false, true, false, true]; // 0101 Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks! ...

Mastering Node.js: Writing to a Write Stream on the 'finish' Event

I'm currently using Node.js streams to process a text file line by line, apply some transformations, and then generate an SVG file based on the data. However, I am facing an issue where when I try to write the closing tag (</svg>) after all pro ...

Encountering issues with extension CLI - "Unable to utilize the import statement outside a module"

Recently, I've been attempting to integrate the Afinn-165 node package (https://www.npmjs.com/package/afinn-165) into my Google Chrome extension. The goal is to analyze the sentiment of text scraped from each page. Being a novice in web development, I ...

Execute the 'loadURL' function in the electron-Angular project when the Angular Compiler has finished preparing

When working with electron-Angular tutorials, it is common to create the window and load index.html from localhost after a set timeout. You'll often come across instructions similar to this: // set timeout to render the window not until the Angular c ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...