Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

abdul-wahab picture abdul-wahab · Nov 12, 2017 · Viewed 105.6k times · Source

What is the bare minimum and Angular4's native way to slide in and slide out a container element?

e.g.

<div ngIf="show">
    <!-- Content -->
</div>

Slide In Content (from top to down just like jQuery.slideDown()) when show turns to true.

Slide Out Content (suitably with ease-out effect) when show turns to false.

Answer

Hoff picture Hoff · Nov 12, 2017

First some code, then the explanaition. The official docs describing this are here.

import { trigger, transition, animate, style } from '@angular/animations'

@Component({
  ...
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({transform: 'translateY(-100%)'}),
        animate('200ms ease-in', style({transform: 'translateY(0%)'}))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
      ])
    ])
  ]
})

In your template:

<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>

I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.

The animations part in human language:

  • We're naming this animation 'slideInOut'.
  • When the element is added (:enter), we do the following:
  • ->Immediately move the element 100% up (from itself), to appear off screen.
  • ->then animate the translateY value until we are at 0%, where the element would naturally be.

  • When the element is removed, animate the translateY value (currently 0), to -100% (off screen).

The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.

Hope this helps!