0
点赞
收藏
分享

微信扫一扫

Angular 动画简介


Angular 的动画系统是基于 CSS 功能构建的,这意味着你可以 "动" 浏览器认为可动的任何属性。包括位置、大小、变形、颜色、边框等。

快速上手

Angular 主要的动画模块是 @angular/animations 和 @angular/platform-browser。当你使用 CLI 创建新项目时,这些依赖会自动添加到你的项目中。

步骤一:启用动画模块

src/app/app.module.ts 里引入module

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

@NgModule({
  imports: [
    BrowserAnimationsModule
  ],
})

步骤二:添加动画的元数据属性

在组件的 @Component() 装饰器中,添加一个名叫 animations: 的元数据属性。.

Angular 动画简介_触发器

简单转场动画

下面我以一个简单的心动动画为例

Angular 动画简介_Angular 动画简介_02

about.component.html 

<div style="height: 100px;width: 100px;display: flex;justify-content: center;align-items: center;">
  <svg viewBox="0 0 25.51 22.91" style="overflow: visible;cursor: pointer;" (click)="click()" [@changeSvgSize]='currentState'>
    <path
      d="M12.76,22.3c0,0-12.26-8.33-12.26-14.95c0-2.57,1.8-6.85,6.19-6.85
    c2.43-0.12,4.74,1.07,6.07,3.11c1.32-2.04,3.63-3.23,6.07-3.11c4.39,0,6.19,4.28,6.19,6.85C25.01,13.97,12.76,22.3,12.76,22.3z"
      style="fill: #eb5505;"></path>
  </svg>
</div>

about.component.ts

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

@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css'],
  animations: [
    trigger('changeSvgSize', [
      state('initial', style({
        width: '25px',
        height: '23px'
      })),
      state('final', style({
        width: '20px',
        height: '20px'
      })),
      transition('initial=>final', animate('150ms')),
      transition('final=>initial', animate('150ms'))
    ]),
  ]
})
export class AboutComponent{
  public currentState = 'initial';

  constructor() { }

  click(): void {
    this.currentState = this.currentState === 'initial' ? 'final' : 'initial';
    setTimeout(() => {
      this.currentState = this.currentState === 'initial' ? 'final' : 'initial';
    }, 150);
  }

}

state() 函数来定义不同的状态

使用 style() 函数来定义一组与指定的状态名相关的样式。注意,样式的属性必须是小驼峰 格式的。

transition() 接受两个参数:第一个参数接受一个表达式,它定义两个转场状态之间的方向;第二个参数接受一个或一系列 animate() 函数

trigger()会定义动画需要触发器名称

将触发器附加到 HTML 模板中方法:<div [@triggerName]="expression">...</div>

要学习更复杂动画请参照中文文档

https://angular.cn/guide/transition-and-triggers

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

举报

相关推荐

0 条评论