Angular2 Animation - Animate opacity, but not display-attribute

rakete picture rakete · Feb 9, 2017 · Viewed 8.2k times · Source

I want to show and hide my modal component with Angular2 animations. At the moment this is my code:

animations: [
    trigger('modalState', [
      state('true', style({
        display: 'block',
        opacity: '1'
      })),
      state('false',   style({
        display: 'none',
        opacity: '0'
      })),
      transition('* => *', animate('200ms ease'))
    ])
  ]

The problem: At the moment the display block is set after 200ms. So you can't see the animated opacity. The display should be set directly after event.

How to do this?

Answer

Lev Himmelfarb picture Lev Himmelfarb · Nov 13, 2019

You can use animation hooks for discrete CSS properties such as display. So, your animation would include only the opacity:

animations: [
  trigger('modalState', [
    state('true', style({
      opacity: '1'
    })),
    state('false', style({
      opacity: '0'
    })),
    transition('* => *', animate('200ms ease'))
  ])
]

And then in your template you can use animation start/end hooks to toggle the display:

<div
  [@modalState]="isShown"
  (@modalState.start)="$event.element.style.display = 'block'"
  (@modalState.done)="$event.element.style.display = ($event.toState ? 'block' : 'none')">
  ...
</div>

Assuming isShown is Boolean.