The Angular animation using :leave/:enter appears to only have an effect when the page is refreshed

I'm in the process of developing an Angular animation, but it seems like it's not working as expected at the moment.

Here is my code snippet:

trigger("fadeInOut", [
  transition("* => *", [
    query(":enter", [style({ opacity: 0 })], { optional: true }),
    query(
      ":leave",
      [style({ opacity: 1 }), animate("2s", style({ opacity: 0 }))],
      { optional: true }
    ),
    query(
      ":enter",
      [style({ opacity: 0 }), animate("2s", style({ opacity: 1 }))],
      { optional: true }
    )
  ])
])

This code aims to achieve a simple fadeIn/fadeOut effect when adding or removing elements. Here is how it looks in HTML:

<main @fadeInOut class="container">
    <div *ngIf="state">State is true</div>
    <div *ngIf="!state">State is false</div>
</main>

You can view the result on Stackblitz. When toggling the state, a different div element should be displayed, but without any animation. However, upon reloading, a nice fadeIn effect can be observed.

I attempted to apply the @fadeInOut* directly on the div elements, but that did not resolve the issue. It appears there may be a misunderstanding on my part regarding the use of transition and/or query. Any advice or guidance would be greatly appreciated!

Answer №1

It seems like what you're looking for is a transition instead of a query. Here's the updated angular animations code:

trigger("fadeInOut", [
  transition(':enter', [
    style({ opacity: 0 }),
    animate('2s', style({ opacity: 1 })),
  ]),
  transition(':leave', [
    animate('2s', style({ opacity: 0 })),
  ]),
])

You can apply these animations directly to the individual div elements instead of their parent:

<main class="container">
    <div *ngIf="state" @fadeInOut>State is true</div>
    <div *ngIf="!state" @fadeInOut>State is false</div>
</main>

Answer №2

Perhaps I have found a solution, but it seems that the statement "Angular Animations are specifically created for elements being added or removed from the DOM" is accurate.

Let's explore the solution provided by @William Juan.

A simple CSS trick :

  1. Set the class .container as relative
  2. Make the children (the 2 divs) absolute, with specific values for top, left, etc. (use same values for overlapping effect)

In your .ts file, introduce a delay :

  trigger("fadeInOut", [
    transition(':enter', [
      style({ opacity: 0 }),
      animate('1s 1s',  style({ opacity: 1 })),
    ]),
    transition(':leave', [
      animate('1s', style({ opacity: 0 })),
    ]),
  ])

This setup will create a fade in-out visual effect.

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

Send the update and overview directives to different components

In my Angular application, I have created a dashboard with libraries acting as widgets. When I refresh or execute a dashboard-specific command within the dashboard, all the widgets also refresh and receive the same command. Currently, I am using the .forRo ...

Create a new TypeScript object without any initial properties, then proceed to define its attributes

Working on honing my skills with Angular Forms utilizing the template-driven approach. My goal is to construct a user interface to display the output of my data in this structure: <hr> <div class="well well-lg"> ...

When the keyboard appears, the Ionic 2 form smoothly slides upwards

I am currently working with the most recent version of Ionic 2. In my code, I have a <ion-content padding><form></form></ion-content> containing a text input. However, when attempting to enter text on an Android device, the keyboard ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Error in Firebase Functions: Promises must be properly managed

Currently, I am in the process of creating a Firebase function using TypeScript to deliver push notifications to multiple users. However, whenever I execute the command firebase deploy --only functions, TSLint flags an error stating "Promises must be han ...

SharePoint Online / Angular - Issue: Unhandled Error: Zone is already loaded

I recently completed a project in Angular and integrated it into a SharePoint page using the Content Editor. Everything was running smoothly until yesterday, when I encountered an error while loading the page. zone-evergreen.js:42 Uncaught Error: Zone alre ...

Unable to locate TypeScript's before() and after() methods

Having trouble running TypeScript tests with Jest/SuperTest - when running npm test, I encounter the following errors: Which package am I missing or not importing? FAIL test/test.ts ● Test suite failed to run test/test.ts:8:3 - error TS2304: Ca ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

The issue at hand is that the component is not recognized as an NgModule

I am encountering an issue with my NgModule configuration: @NgModule({ imports: [ CommonModule ], exports: [ SP21LoadingBar ], declarations: [SP21LoadingBar] }) export class SP21LoadingBarModule { } When I run the CLI, ...

Puppeteer: Simulating WebSocket Connections

How can I simulate WebSocket communication in Puppeteer? I'm currently testing my web application without a real backend and have been able to mock Ajax calls using the on request handler. However, I now need to test how my application responds to Web ...

Exploring the capabilities of Swiper within the Angular 17 framework

Currently, I am delving into the world of Angular 17 for a new project and looking to incorporate Swiper for a dynamic carousel feature. Despite my best efforts, I have encountered some obstacles while attempting to make it work. Has anyone in this commun ...

Exploring the inner workings of Angular v4.4 and gaining insight into the roles of platformBrowserDynamic and PlatformRef

Recently, I have come into possession of an Angular 4.4 application that utilizes Webpack v3.5 and TypeScript v2.3.3. Struggling to decipher the imported code, I am at a loss understanding its functionality and correctness. To simplify matters for analysis ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

Ways to restrict the width of an Ionic application

I currently utilize Ionic for mobile devices such as phones and tablets. The appearance on phones is stunning. However, it appears too elongated on tablets. Anyone know how to limit the width of the app on all pages? https://i.sstatic.net/IJKP6.png ...

Utilizing a custom vision model exported for TensorFlow JS to analyze an image input

Hello, I'm just starting out with tensorflow.js and tensorflow. Here's the situation: We've trained a model using Custom Vision to recognize different hair lengths (short, mid, long) from an image. The model was exported as a *.pb file alon ...

Using TypeScript to ensure the correct typing for the return type of AsyncThunk when utilizing the 'unwrapResult' method from Redux Toolkit

Struggling to determine the appropriate return type for an AsyncThunkAction in order to utilize it with the unwrapResult method from Redux Toolkit (refer to: Redux Tookit: Unwrapping Result Actions): Here is how the Async thunk is declared in the Slice: e ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Ways to verify if the output from translate.instant has been properly translated at least once

With ngx-translate, I have implemented the following function and my goal is interface IWidgetFilterValue = { label: string; value: string; } getSortedOptions(filterOptionsArr: IWidgetFilterValue[]): IWidgetFilterValue[] { const filterOptionsArrNew = ...

Angular 8: Master the art of HTML binding

I am facing an issue with displaying HTML content in Angular 8. **Note: The HTML template I receive from the database as JSON data needs to be displayed in Angular. I am fetching this template and saving it in a variable (e.g., plot), then passing that va ...

Uncertain about the distinction between reducers and dispatchers when it comes to handling actions

I'm feeling a bit confused regarding reducers and dispatchers. While both receive actions as parameters, it doesn't necessarily mean that the actions I use in my dispatchers are the same as those used in my reducers, correct? For example, if I h ...