In-Depth guide into animations in Angular

1 Like

Thank you for this well-written guide, @williamjuan!

1 Like

@williamjuan thanks for the comprehensive guide.

I’m curious, is it possible to listen to host’s *ngIf events (:enter or :leave) inside a directive like we listen to @-triggers at components (to animate programmatically with the builder after that)?

Hey @oblogera,
Thats a really interesting idea. If I understand your question correctly, you’re thinking of something like:

<div *ngIf="someCondition" animateMe></div>

where animateMe is a directive that will apply :enter and :leave animations?

Directives don’t currently support angular animations the same way components does, however, you are able to use the AnimationPlayer and AnimationBuilder which accepts the same AnimationMetadata that you use in angular animations. You would need to handle the trigger separately by some flag that you pass in.

 @Input()
  set show(show: boolean) {
    const metadata = show ? this.fadeIn() : this.fadeOut();

    const factory = this.builder.build(metadata);
    const player = factory.create(this.el.nativeElement);

    player.play();
  }

fadeIn(): AnimationMetadata[] {
    return [
      style({ opacity: 0 }),
      animate('400ms ease-in', style({ opacity: 1 })),
    ];
  }

With regards to *ngIf, I believe (correct me if I’m wrong) directives gets destroyed with the component that it is attached to. You might be able add enter animation, but I’m not sure if the directive would be able to handle an exit animation.

Yea, looks like it’s not possible to delegate this ngif-bound logic completely to a directive. Thanks anyway :+1: