0%

Angular2 组件动画

Angular可以通过在一定的时间内将组件的css样式过渡切换成另一种样式来实现动画。下面的例子是将一个盒子从黄色背景切成蓝色,并且修改margin-left来移动位置。
效果如下:
angular 动画

AnimationComponent:

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

@Component({
  selector: 'app-animation',
  templateUrl: './animation.component.html',
  styleUrls: ['./animation.component.css'],
  animations:[
    //在position状态改变时,触发动画
    trigger('position',[
      //position为left时的样式
      state('left',style({
        'margin-left': 0,
        'background-color':'yellow'
      })),
      //position为right时的样式
      state('right',style({
        'margin-left': 200,
        'background-color':'blue'
      })),
      //状态切换时的动画设置
      transition('left => right',animate('1000ms ease-in')),
      transition('right => left',animate('1000ms ease-out'))
    ])
  ]
})
export class AnimationComponent implements OnInit {

  constructor() { }
  currentPosition='left';
  ngOnInit() {
  }

  /**
   * 按钮事件,切换状态
   */
  togglePosition() {
    if(this.currentPosition=='left') {
      this.currentPosition='right';
    }else{
      this.currentPosition='left';
    }
  }
}

模板:

  <div id="brick" [@position]="currentPosition"></div>
  <button (click)="togglePosition()">切换位置</button>

css:

#brick {
  width: 20rem;
  height: 10rem;
  background-color: aqua;
  margin-left: 0;
}