Animating CSS styles when ngOnDestroy is called or when an element is removed from

Incorporating Angular 7, I am eager to execute a CSS animation on the host element of a component during its removal from the DOM when it is destroyed.

  • Upon utilizing the ngOnDestroy method, the host element has already been removed from the DOM.
  • Alternatively, if opting for a MutationObserver that monitors removed elements in the parent component, the same issue arises as the element is no longer present in the DOM.

What other strategies are available to achieve this and what would be the most efficient approach? Notably, I prefer not to rely on jQuery or any of its plugins.

Answer №1

When approaching the issue from a different angle, one possible solution involves utilizing Angular Animations' void state along with *ngIf.

To start, import the BrowserAnimationsModule into your app.module.ts:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
  imports: [ BrowserAnimationsModule ]
})

In the parent component that contains the component you wish to remove, you can apply the void state animation by using *ngIf. For example:

@Component({

  animations: [
    trigger('animateDestroy', [
      state('void', style({ opacity: '0' })),
      transition('* => void', animate('500ms ease'))
    ])
  ],

  template: `
    <component-to-destroy *ngIf="someBoolean" @animateDestroy>
    </component-to-destroy>
  `

})
export class ParentComponent {
  someBoolean = true;
}

By changing the value of someBoolean to false, Angular will remove the component from the DOM due to the presence of *ngIf. Prior to removal, the animateDestroy trigger with * => void instructs Angular to animate the element out before eliminating it from the DOM.

For more information on Angular Animations and the void state, refer to the official documentation.

This approach may not rely on CSS directly, but it offers similar outcomes. It allows the template to control the "destroyed or not" state of the component using a boolean instead of requiring complex logic within the class.

I hope this explanation proves helpful in navigating this scenario.

Answer №2

Consider utilizing a service for this task.
Take a look at the concluding section of this webpage.

To implement this, you need to establish an observable within the service and invoke it in the onDestroy method of your component. Afterwards, you should subscribe to this event in your parent component.

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

What is the best way to dynamically add anchor tags to table cells using TypeScript?

I'm having trouble inserting a functional anchor tag within an HTML table that I am generating dynamically using TypeScript. When I try to add the anchor tag using innerHTML and append it to the cell, only the text shows up in the table and the link d ...

Tips for eliminating infinite loops in NGRX or NGXS architecture

In my application, I have a component called user-personal-details.component.ts, which is designed to stay in sync with the user data stored in the Store. @Select() user$: Observable<IUser>; user:IUser; ngOnInit() { this.user$.subscribe((user:IUse ...

Ways to troubleshoot and resolve the npx create-next-app issue

Every time I try to create a new app using npx create-next-app@latest --typescript, it keeps giving me this error message: npm ERR! code ENETUNREACH npm ERR! syscall connect npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/create-n ...

Is there a way to store the selected item from a dropdown list in Angular 2?

I am struggling with saving the selected item from a dropdown list. Below is the code I have been working on. Currently, I am able to console.log the values of selectedProject.id and selectedProject.name using a button and the function outData. However, I ...

Angular - Set value on formArrayName

I'm currently working on a form that contains an array of strings. Every time I try to add a new element to the list, I encounter an issue when using setValue to set values in the array. The following error is displayed: <button (click)="addNewCom ...

Problems encountered with iframe-resizer in Next.js: Notification of GPLv3 License and Error message indicating "iFrame not responding"

My project in Next.js 14 involves creating a testimonial feature with testimonials displayed through an iframe. The aim is to generate an iframe tag (and potentially necessary script tags) that, when inserted into any website's HTML, allows users to v ...

When trying to fetch and structure JSON data in Angular 6, the console displays "undefined" as the output

I'm currently exploring how to retrieve JSON data from an API, parse it, map it to my custom type, and then showcase it in an Angular Material datatable. Despite my efforts, the console output indicates that the value is undefined. I haven't even ...

Is there intellisense support for Angular 2 templates in Visual Studio?

Is it possible for Visual Studio to provide autocomplete suggestions for properties of a Typescript component within a separate HTML view template? ...

Sequentially subscribe to observables and execute tasks in between them

Struggling to properly chain 3 interdependent observables using the rxjs concat operator. Need to perform actions between the first and second observable, as well as after the last one. The challenge lies in passing the result of the first observable to th ...

Exploring the Dynamic Display of Nested JSON Objects in Angular 6

Struggling with a complex issue and feeling lost on how to approach it. I'm currently working with Angular 6. The challenge at hand involves handling JSON data in my project. While accessing simple data like "id" or "certificate" is easy, I'm en ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...

Using Angular: Accessing a specific object property within a collection for a Form input

Need assistance with handling a collection in an Angular component: collection: collectionAbs[]; export interface collectionAbs{ name: string; prop: string; secondProp: number; } Initialization: this.collection.forEach((item ,index) = ...

Having trouble importing a TypeScript module from the global node_modules directory

I have a library folder located in the global node modules directory with a file named index.ts inside the library/src folder //inside index.ts export * from './components/button.component'; Now I am trying to import this into my angular-cli ap ...

Use Angular or Laravel to translate API response data before it is sent to the frontend

I am currently working with an Angular frontend and a Laravel backend. I have an API that returns color names in an array, which I need to translate based on the default language setting. In both my frontend and backend, I have two JSON files named en.json ...

Displaying related objects information from a single object in AngularFire2 can be achieved by following these steps

As a newcomer to Angular and Firebase, I apologize if my question seems basic. I'm seeking guidance on how to display related object information from one object in angularfire2. Specifically, I want to show the role names assigned to a user. Here is ...

What is the best way to use a generic callback function as a specific argument?

TS Playground of the problem function callStringFunction(callback: (s: string) => void) { callback("unknown string inputted by user"); } function callNumberFunction(callback: (n: number) => void) { callback(4); // unknown number inputt ...

Unable to utilize ngForm when values are already predefined

I have an Angular application with Ionic 4. Here is the HTML code for my form: <form #formAuth="ngForm" (ngSubmit)="sendCode(formAuth)" method="post"> <ion-select placeholder="Country" ngModel name="area_code" interface="modal"> <io ...

Tips for saving images in cookies with Angular

Exploring ngx-cookie-service in Angular for a static website project. How can we store images in cookies and retrieve them in another component? ...

A guide on integrating third-party npm modules/packages into an Angular 8 application

As someone who is new to Angular and TypeScript, I am finding it challenging to add a 3rd party module or package to my Angular app. After spending hours searching online, I have yet to come across a simple guide for this process. The specific problem I a ...

Using Typescript to import a module and export a sub function

I am currently using mocha for testing a function, but I have encountered an error while running the test file. The structure of my files is organized as follows: server |-test | |-customer.test.ts |-customer.js Here is the content of the customer.js fi ...