angulartypescriptangular-animations

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


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.


Solution

  • First some code, then the explanation. 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:

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