Animation in Angular

Anh-Thi Dinh
draft
Notes in this post are just blocks of examples. They're not a full guide to use animation in Angular. For a full guide, read the official documentation.

:enter and :leave

1transition ( ':enter', [ ... ] );  // alias for void => *
2transition ( ':leave', [ ... ] );  // alias for * => void

With parameters

1// Without state
2animations: [
3  trigger('grow', [
4    transition('* <=> *', [
5      style({height: '{{startHeight}}px', opacity: 0}),
6      animate('.5s ease'),
7    ], {params: {startHeight: 0}})
8  ])
9]
1// With state
2animations: [
3  trigger('dropdownAnimation', [
4    state('true', style({
5      maxHeight: '{{numberOfDropdownItems}}px',
6      overflow: 'hidden'
7    }),  {params: {numberOfDropdownItems: 1}}),
8    state('false',   style({
9      maxHeight: '0px',
10      overflow: 'hidden',
11      opacity:0
12    })),
13    transition('true => false', animate('600ms ease-out')),
14    transition('false => true', animate('1000ms ease-in'))
15  ])
16]

Make a reusable component

1// fade-in-out.animation.ts
2import { trigger, style, animate, transition } from '@angular/animations';
3
4export const fadeInOut = trigger('fadeInOut', [
5  transition(':enter', [style({ opacity: 0 }), animate('200ms', style({ opacity: 1 }))]),
6  transition(':leave', [animate('200ms', style({ opacity: 0 }))])
7]);
1<!-- users.component.html -->
2<div @fadeInOut>Content</div>
1// users.component.ts
2import { fadeInOut } from './fade-in-out.animation';
3@Component({
4  selector: 'app-users',
5  templateUrl: './users.component.html',
6  styleUrls: ['./users.component.scss'],
7  animations: [fadeInOut]
8})
9export class UsersComponent implements OnInit {
10	// Some logics
11}

Trigger with states

1<!-- data.component.html -->
2<div [@dataListTabs]="dataListTabsState">
3  Content
4</div>
1// data.component.ts
2import { animate, state, style, transition, trigger } from '@angular/animations';
3
4@Component({
5  selector: 'app-data',
6  templateUrl: './data.component.html',
7  styleUrls: ['./data.component.scss'],
8  animation: [
9    trigger('dataListTabs', [
10      state('expanded', style({ opacity: '1' })),
11      state('collapsed', style({ opacity: '0' })),
12      transition('collapsed => expanded', animate('0.4s ease-out')),
13      transition('expanded => collapsed', animate('0.01s ease-out'))
14    ]),
15  ]
16})
17export class DataComponent implements OnInit {
18  dataListTabsState: 'expanded' | 'collapsed';
19  // Some logics for dataListTabsState
20}
Loading comments...