Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 309
abdul-wahab Avatar asked Nov 12 '17 12:11

abdul-wahab


People also ask

Which animation strategy would you use to apply multiple styles for a transition?

The keyframes() function in Angular allows you to specify multiple interim styles within a single transition, with an optional offset to define the point in the animation where each style change should occur.

Which animation strategy would you use if there were multiple animations that had to occur at the same time?

A staggered animation consists of sequential or overlapping animations. To create a staggered animation, use multiple Animation objects.


1 Answers

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:

  • 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!

like image 183
Hoff Avatar answered Oct 16 '22 07:10

Hoff