DEV Community

Cover image for A Guide To Angular Animations and Transition
Zakarya Noori
Zakarya Noori

Posted on

A Guide To Angular Animations and Transition

I had hard times figuring out how angular animation works, so I am making your job easier.

in your component module import BrowserAnimationsModule or any other module that contains BrowserAnimationModule like CommonModule as Follows:

imports: [
  BrowserAnimationsModule
]
Enter fullscreen mode Exit fullscreen mode

in your component add animations inside your component like following I am triggering fadeIn transition animation:

@Component({
  selector: 'app-name',
  templateUrl: './name.component.html',
  styleUrls: ['./name.component.scss'],
  animations: [
    trigger('fadeIn', [
      state('open', style({
        opacity: 1,
        pointerEvents: 'all'
      })),
      state('closed', style({
        opacity: 0,
        pointerEvents: 'none'
      })),
      transition('open => closed', [
        animate('3s')
      ]),
      transition('closed => open', [
        animate('3s')
      ])
    ])
  ]
})
Enter fullscreen mode Exit fullscreen mode

Then in your HTML use it as follows, I am triggering fadeIn animation based on showAnimation variable condition you can use your own:

<div class="fade" [@fadeIn]="showAnimation ? 'open' : 'closed'">
  This will fade in
</div>
<button (click)="showAnimation = !showAnimation">Toggle fade</button>
Enter fullscreen mode Exit fullscreen mode

you have to add transition for your element in css:

.fade {
  transition: all .4s ease;
}
Enter fullscreen mode Exit fullscreen mode

Your animation should work now
you can animate transform and other properties too, I am just using opacity to fade.

Top comments (0)