LoginSignup
14

More than 5 years have passed since last update.

Angular2 animation

Posted at

背景

Angular2のAnimationsに関するドキュメンが少なかったので書きました。公式ドキュメントを参考にしております。

lacoさんの記事より少し新しい内容になっております

概要

ウェブアプリケーションにアニメーションを導入することで、リッチでスムーズなインターフェイスを提供する事が出来ます。パフォーマンスが気になるところですが、CSSアニメーションを使うことでネイティブと同等のパフォーマンスで動くアニメーションを作ることが出来ます。

Angular Animations

Angularアニメーションは、WebAnimationAPIがサポートされているブラウザ上で動きます。各ブラウザのサポート状況はこちらで確認できます。

非対応のブラウザについてはこちらのポリフィルを読み込ませて下さい。
より軽量なポリフィルをAngularチームが開発中で近日中に公開するそうです。

Let's build

それではelementの属性値によって変化する(2パターン)アニメーションを作ってみましょう。

まずは必要なモジュールを@angular/coreからimportしましょう

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

Animationsは@Component内で宣言します

@Component({
  ...
  animations: []
})

アニメーションのトリガをtriggerを使い作成します。

@Component({
  ...
  animations: [
    trigger('buttonState', [])
  ]
})

今回は再生/停止ボタンを作りますので、(ボタンのステータス変化をトリガにする)ということで、buttonStateという名前にします

トリガのステータス(play、stop)をstateで宣言します。
また、その際のスタイルをstyleで宣言します。

  animations: [
    trigger('buttonState', [
      state('play', style({
        "background-image": 'url("/images/play.svg")',
        transform: 'scale(1.1)'
      })),
      state('stop', style({
        "background-image": 'url("/images/stop.svg")',
        transform: 'scale(1)'
      }))
    ])
  ]

playの際は背景イメージを変更し、ボタンの大きさを少し大きくします。
stopの際は背景イメージを変更し、ボタンの大きさをもとの大きさに戻します。

次に、トリガのステータスが変化した際のアニメーションをtransionで宣言します。

  animations: [
    trigger('buttonState', [
      state('play', style({
        "background-image": 'url("/images/play.svg")',
        transform: 'scale(1.1)'
      })),
      state('stop', style({
        "background-image": 'url("/images/stop.svg")',
        transform: 'scale(1)'
      })),
      transition('play => stop', animate('100ms ease-in')),
      transition('stop => play', animate('100ms ease-out'))
    ])
  ]

playからstopに変化した際は、animateを使い100ミリ秒でイージングで変化させる
stopからplayに変化した際も同様

ここまででアニメーションの作成は完成です。
次にテンプレートに、このアニメーションをアタッチします。

<button class="btn" @buttonState="state" (click)="onClick()"></button>

アニメーションさせたいエレメントに対して"@トリガ名"とした属性を付け加えます。valueには、現在のステータスが入ったプロパティを指定します。

次に、現在のステータスが入るプロパティを宣言します。

@Component({
  ...
})
export class AppComponent implements OnInit{
  public state : string;

    ngOnInit(): void {
      this.state = "stop";
    }

    private onClick() {
      this.state = this.state === "play" ? "stop" : "play";
    }
}

stateプロパティを宣言し、ngOnInitで初期化します。
クリック時に現在の値から新しいプロパティ値を設定します

以上で完成になります。

完成したサンプルは下記をご参考下さい
GitHub

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14