Angularによるスライドアニメーション

Angularによるスライドアニメーション

Angularでいわゆるスライドアニメーションを実装するための方法です。

Angular 4 +での初期設定

Angular4 よりanimation系は@angular/coreより除外されていますので、@NgModule内で@angular/platform-browser/animationsより取得したBrowserAnimationsModuleをimportsに設定しておき、@angular/animations より trigger, state,style, transition, animate, keyframesをimportしておきます。

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
.
.
.
@NgModule({
  declarations: [
    App,
  ],
  imports: [
    ...
    BrowserAnimationsModule,
    ...
  ],
  bootstrap: [App]
})
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';

Angular 2での初期設定

Angular2系ではanimation系がまだ@angular/coreに含まれているので@angular/coreよりstate, trigger, style, transition, animateをインポートするだけでよいです。

import { state, trigger, style, transition, animate} from "@angular/core";

共通設定

Angularでは@Componentにanimationsとしてアニメーションを設定することができます。

下記のサンプルではtrigger()に指定できるアニメーション名に「slide」と指定をして、状態が「show」から「hide」になる場合は高さが0に、状態が「hide」から「show」に変更される場合は高さがautoになるようにアニメーションを設定しています。

アニメーション対象の要素(今回はul要素)に 「[@アニメーション名] = アニメーション状態」としてアニメーションが設定でき下記のサンプルではmySlideStateをアニメーション状態として定義しています。

最後にアニメーション対象の要素にCSSで「overflow:hidden」を指定すれば完了です。

動作サンプル

@Component({
  selector: 'app',
  template: `
    <input (click)="mySlideState = 'show'" type="button" value="開く" />
    <input (click)="mySlideState = 'hide'" type="button" value="閉じる" />
    <ul [@slide]="mySlideState">
      <li>list1</li>
      <li>list2</li>
      <li>list3</li>
      <li>list4</li>
      <li>list5</li>
    </ul>
  `,
  styles: [`
    ul{
      overflow:hidden
    }
  `],
  animations:[
    trigger('slide',[
      state('show', style({
        height:'*'
      })),
      state('hide', style({
        height:'0'
      })),
      transition('show => hide', animate('400ms ease-in')),
      transition('hide => show', animate('400ms ease-out'))
    ])
  ]
})
export class App {
  mySlideState:string = 'hide';
}

これでアニメーション状態が「show」から「hide」、「hide」から「show」に変わるたびにスライドアニメーションが行われます。

スポンサードリンク

«続:AngularでChangeDetectionによるパフォーマンスチューニング | メイン | Web制作の現場で使う jQueryデザイン入門 [改訂新版] 12刷決定»