Introduction to Angular animations

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div style="margin-left: 10px;margin-top: 10px;">
  <button class="btn btn-primary" (click)="onAnimate()">Animate</button>
  <br><br>
  <div [@divState]="state" style="width: 100px;height: 100px;"></div>
</div>

app.component.ts

import {Component} from '@angular/core';
import {
  trigger,
  state,
  style,
  animate,
  transition,
  // ...
} from '@angular/animations';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('divState', [
      state('normal', style({
        'background-color': 'red',
        transform: 'translateX(0px)'
      })),
      state('highlighted', style({
        'background-color': 'blue',
        transform: 'translateX(100px)',
      })),
      transition('normal => highlighted', [animate(300)]),
      transition('highlighted => normal', [animate(800)])
    ])
  ]
})
export class AppComponent {
  title = 'animations';
  state = 'normal';

  onAnimate() {
    // switch state
    if (this.state === 'normal') {
      this.state = 'highlighted';
    } else {
      this.state = 'normal';
    }
  }
}

References
https://angular.io/guide/animations

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.