How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds.

If we clear the container using this.container.clear(), the removal of the element is not animated. The animations attribute in the code snippet below controls this behavior:

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

How can we ensure that the leave animation is triggered in this scenario?

Answer №1

To update your alert.component.ts file, make the following changes:

import { Component, Input, EventEmitter, Output } from '@angular/core';
import { trigger, style, animate, transition } from '@angular/animations';

@Component({
  selector: "alert",
  template: `
     <section [@fadeInOut]>
     <h1 (click)="output.next('output')">Alert {{type}}</h1>
    <section>
  `,
  styles: [`
  :host {
    display: block;
    overflow: hidden;
  }`],
  animations: [
    trigger('fadeInOut', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate(5000, style({ opacity: 1 }))
      ]),
      transition(':leave', [
        animate(5000, style({ opacity: 0 }))
      ])
    ])
  ],
  host: { '[@fadeInOut]': 'in' }
})
export class AlertComponent {
  @Input() type: string = "success";
  @Output() output = new EventEmitter();
}

For more information, visit https://stackblitz.com/edit/angular-animate-dynamically-created-component?file=app%2Fhello.component.ts

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

Utilizing React JS to Export Axios Response

I have an getAllUsers.js File that retrieves all users from the API. import axios from 'axios' export const fetchData = async () => { let response try { response = await axios.get('http://127.0.0.1:8000/api/users') } catc ...

``Is there a way to position an image at the center in Python dash?

Can someone help me with centering an image in my Flask dash app? Here is the code I have: import dash from dash import html, dcc import dash_bootstrap_components as dbc app = dash.Dash(__name__) app.layout = html.Div([ dbc.CardImg(src=r'assets/ ...

Using a PHP variable to trigger the jQuery .show() function

I'm attempting to trigger jQuery .show() events based on PHP variables. Below is my PHP code (retrieved from a form submission on another page): $last_pic_displayed = trim($_POST["last_pic_displayed"]); if (strlen($last_pic_displayed) <= ...

What is the best way to ensure that my transitionend event is triggered?

I'm currently exploring the <progress> element and attempting to incorporate a CSS transition to achieve a smooth progress bar effect as its value increases. Despite my efforts, I can't seem to trigger JS after the transitionend event occur ...

Utilizing Redux with React to fetch and handle JSON data from given API endpoint

The assignment I'm working on requires us to fetch JSON data from a specific endpoint called url and display it in an Excel-like table using React, Redux, and Redux-Thunk. I successfully managed to retrieve and display the data in a table by utilizin ...

Here's how you can transfer the AceEditor value to the component state in ReactJS by utilizing the onClick event of a button

I'm facing a challenge implementing a customized CodeMirror using ACE Editor. I've experimented with incorporating state alongside the 'onClick' button parameter, but I haven't been successful in making it functional. import Rea ...

Unit testing in Angular - creating mock services with observables

I'm currently facing an issue with my unit tests for a component that subscribes to an Observable from the service DataService in the ngOnInit() lifecycle hook. Despite my efforts, I keep encountering the error message TypeError: Cannot read propertie ...

How to efficiently pass dynamic props in Next.js persisting layoutuciary

When setting up a persistence layout, I utilize the getLayout function on each page as shown below: import { Layout } from 'hoc'; const Page = () => { return ( <div>hello</div> ); }; Page.getLayout = function getLayout(pa ...

"Twice the loading of Meteor templates: once with an undefined collection, and once with it

After searching various resources for solutions to my issue, I stumbled upon this helpful and . Both of these links provided valuable insights. The issue I'm facing is that one of my templates is loading twice - first with the collection undefined, ...

Expanding the capabilities of generic functions in TypeScript using type variables

When working with generics in TypeScript, it is often beneficial for a function that accepts generically-typed arguments to have knowledge of the type. There exists a standard approach to achieve this using named functions: interface TestInterface<T> ...

Filtering substrings in an Angular data resource

DEFAULT_RECORDS = [{ id: 1, name: 'John Evans', number: '01928 356115' },{ id: 16, name: 'Murbinator', number: '053180 080000' }]; - retrieveEntries: function (name) { var foundRecords = {}; ...

Endlessly streaming data is requested through HTTP GET requests

I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because ...

Stop header background image from loading on mobile browsers by utilizing the <picture> tag

Is there a method to utilize the <picture> element in order to prevent a page from downloading an image when viewed on a mobile phone? I have a website that features a header image. Unfortunately, due to the site's functionality, using CSS (bac ...

Calculate the total price from a combination of HTML and JavaScript options without altering the values

I'm currently facing an issue in my form where the final price needs to be updated when a different option is selected. I've searched extensively for the problem without success. I've used similar code before, just with different variables a ...

Encountering the 'unsupported_grant_type' error while attempting to retrieve an access token from the Discord API

Having trouble implementing Discord login on my website. When trying to exchange the code for an access token from https://discord.com/api/oauth2/token, I keep getting the error { error: 'unsupported_grant_type' }. This is my code: const ...

Identifying Touch Interaction exclusively on WebGL Canvas within threejs

Currently, I am developing a threejs application that requires input from HTML buttons and utilizes Raycast Detection on touch within threeJS. The issue I am encountering is that when the user clicks an HTML button, the Raycast function is triggered as we ...

Tips for patiently anticipating the resolution of a new promise

Searching for a way to ensure that a promise waits until a broadcast is fired, I came across some enlightening posts on this platform and decided to implement the technique detailed below. However, it appears that the broadcastPromise does not actually wai ...

Enumerating items in a JSON dataset

I am facing an issue with my JSON data structure: var data = { "conv0": { "id":"d647ed7a5f254462af0a7dc05c75817e", "channelId":"emulator", "user": { "id":"2c1c7fa3", "name":"User1" }, "co ...

Deactivate input areas while choosing an option from a dropdown menu in HTML

I've been working on creating a form and have everything set up so far. However, I'm looking to disable certain fields when selecting an option from a dropdown list. For instance, if the "within company" option is selected for my transaction typ ...

Validation with zod is unsuccessful under certain conditions

I am facing an issue with my form that contains a radio button with three input fields inside it. The submit button is supposed to validate that only one of the input fields is correctly entered. Despite using refine() in zod validation, I cannot get it ...