KevinTale
KevinTale

Reputation: 1858

Cannot do CSS animation in Angular

I'm trying to use a vanilla css animation like so :

div {
  height: 0.5rem;
  width: 1rem;
  background-color: blue;
  transform-origin: left;
  transition: transform 5s;
  transition-delay: 2s;
  transform: scaleX(15);
}

That it just not working at all. The div is displaying at scaleX(15)but with no duration.

It does work properly with CodePen but not with Stackblitz. What am I missing here? Can't CSS animation works with Angular?

Upvotes: 2

Views: 1672

Answers (3)

tim545
tim545

Reputation: 1533

In Angular all CSS styles are encapsulated to the component by default, CSS animations do work in Angular, the framework does not (and cannot) do anything to stop the browser's DOM rendering. As long as your CSS rule selects an element correctly and the applied animations are correct then it will work.

It seems like you need to do 2 things

  1. Make sure your styles are defined within the same component as the div elements that you want to animate (or read the Angular docs about non-encapsulated styles)

  2. Your CSS animation does not work, you need to give it an initial state and then change the style based on an action. A simple example:

.my-div {
  height: 0.5rem;
  width: 20px;
  background-color: blue;
  transition: width 0.3s linear;
}

.my-div.animate {
  width: 200px;
}

In your component you can set the animate class based on some logic for when you want the animation to trigger

In your template:

<div [class.animate]="componentLoaded"></div>

In your component:

export class MyComponent {
  componentLoaded = false;

  ngOnInit() {
    this.componentLoaded = true; // Will trigger animation
  }
}

Upvotes: 1

AliWieckowicz
AliWieckowicz

Reputation: 557

Angular contains css animations

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

https://stackblitz.com/angular/eqxqkpyrdgr?file=src%2Fapp%2Fhero-list-groups.component.ts

Upvotes: 0

stormpanda
stormpanda

Reputation: 23

Your div needs to have an initial state without the transform. transition: transform will only work when a transform value changes. If it's already set from the beginning, there won't be an animation. I made an example where a click on the div triggers the animation, inspired by your CSS snippet.

https://stackblitz.com/edit/angular-uenfjp

Upvotes: 1

Related Questions