Angular 动画教程
Angular 提供了一组丰富的动画库,可以帮助开发者实现丰富的视觉效果。以下是一些关于 Angular 动画的基础知识和使用方法。
基础概念
Angular 动画主要基于 CSS 和 Web Animations API。要使用 Angular 动画,首先需要在模块中导入 BrowserAnimationsModule
。
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [
// ... 其他模块
BrowserAnimationsModule
],
// ...
})
export class AppModule { }
动画步骤
- 定义动画:使用
@Animation
装饰器定义动画。 - 触发动画:使用
trigger
属性触发动画。 - 应用动画:在组件的模板中应用动画。
示例
以下是一个简单的动画示例,它将在按钮点击时显示一个缩放动画。
import { Component } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';
@Component({
selector: 'app-animation-example',
templateUrl: './animation-example.component.html',
styleUrls: ['./animation-example.component.css'],
animations: [
trigger('buttonAnimation', [
state('default', style({
transform: 'scale(1)',
})),
state('expanded', style({
transform: 'scale(1.2)',
})),
transition('default => expanded', animate('300ms')),
transition('expanded => default', animate('300ms')),
]),
],
})
export class AnimationExampleComponent {
expanded = false;
toggle() {
this.expanded = !this.expanded;
}
}
<button (click)="toggle()" [@buttonAnimation]="expanded ? 'expanded' : 'default'">点击我</button>
扩展阅读
Angular