7

With Angular Animations it's possible to add transitions/ animations to elements and their children when they enter or leave the view, like this:

@Component({
  animations: [
    trigger('containerTrigger', [
      transition(':enter', [
        style({ opacity: 0, transform: 'translateY(-10px)' }),
        animate('250ms 100ms', style({ opacity: 1, transform: 'none' })),
      ]),
    ]),
  ]
})

While this works fine, it gets complex very quickly when adding more complex transitons/ animations not only to the selected element but also its children.

Also for someone who is mainly maintining CSS in a project, it might be hard to get used to Angular's animation syntax. Then it's easier to read and maintain a CSS like this:

.container {
  opacity: 0;
  
  &.is-active {
    opacity: 1;
    transition: all 0.2s linear;
  }
}

.container__heading {
  transform: translateX(-10px);

  .container.is-active & {
      transform: none;
      transition: all 0.2s linear;
  }
}

The question: is it possible to add a CSS class on the :enter and :leave events instead of running an Angular Animation?

luiscla27
  • 4,956
  • 37
  • 49
lampshade
  • 2,470
  • 3
  • 36
  • 74
  • Do you want to attach the CSS class to an element and all its children? Or only a specific element? – Federico Andreoli Sep 22 '20 at 12:38
  • The idea is to attach a CSS class to one or multiple elements. The transitions on children can be target with child selectors. This would be very easy to maintain like in the example CSS snippet. But maybe it would only work if every element gets a class, that has a transition. Somehow Angular need to know, when `:leave` is done. – lampshade Sep 22 '20 at 13:16
  • Possible duplicate of [How to give class name to animation state in angular 2/4?](https://stackoverflow.com/q/46097379/2711071). – lampshade Sep 23 '20 at 07:08

1 Answers1

1

Unfortunatly you cant add or remove classes with angulars animation API (see How to give class name to animation state in angular 2/4?).

Binding with e.g. [ngClass] will also not work in this scenario, because when the :enter animation triggers, the element is not in the actual DOM yet, so any applied css will have no impact. https://angular.io/guide/transition-and-triggers#enter-and-leave-aliases

cpc
  • 608
  • 6
  • 22
  • Thanks for finding this duplicate. I searched before posting my question but didn't came up with any result. Too bad though, that it's not possible. – lampshade Sep 23 '20 at 07:12