Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular dynamic component animation leave doesn't work

Let's say I have the following component that I created dynamically.

@Component({
  template: `
    <template #alertContainer></template>
    <button (click)="clear()">clear</button>
    <button (click)="createComponent('success')">Create success alert</button>
  `,
})
export class App {
 @ViewChild("alertContainer", { read: ViewContainerRef }) container;
 componentRef: ComponentRef<any>;

  constructor(private resolver: ComponentFactoryResolver) {}

  clear() {
    this.componentRef.destroy();
  }

  createComponent(type) {
    const factory = this.resolver.resolveComponentFactory(AlertComponent);
    this.componentRef = this.container.createComponent(factory);
  }
}

And the AlertComponent:

@Component({
  template: `
    <section [@fadeInOut]>
     <h1>Alert</h1>
    <section>
  `,
  animations: [
    trigger('fadeInOut', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate(500, style({ opacity: 1 }))
      ]),
      transition(':leave', [
        animate(500, style({ opacity: 0 }))
      ])
    ])
  ],
})
export class AlertComponent {

}

When I create the component the animation works and I get the expected fade in effect. When I click on the clear button which destroys the component I doesn't get any animation effect. What is the problem?

like image 465
undefined Avatar asked Feb 21 '26 02:02

undefined


1 Answers

You are instantiating and destroying the component manually instead of letting the angular framework handle that and thus it's animations. You don't get a leave animation because you destroy (it's gone) the component.

edit

Instead of destroying your component immediately, you can have to clear function trigger the leave animation and use a callback (@fadeInOut.done)="animationDone($event)" to destroy the component.

like image 102
Carsten Avatar answered Feb 22 '26 14:02

Carsten