这是我参与11月更文挑战的第10天,活动详情查看:2021最后一次更文挑战
1. 开场即有的动画
先定义一个动画函数:fade-in.ts
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';
export const flyIn = trigger('flyIn', [
state('in', style({transform: 'translateX(0)'})),
transition('void => *', [
animate(1000, keyframes([
style({opacity: 0, transform: 'translateX(-100%)', offset: 0}),
style({opacity: 1, transform: 'translateX(25px)', offset: 0.3}),
style({opacity: 1, transform: 'translateX(0)', offset: 1.0})
]))
]),
transition('* => void', [
animate(3000, keyframes([
style({opacity: 1, transform: 'translateX(0)', offset: 0}),
style({opacity: 1, transform: 'translateX(-25px)', offset: 0.7}),
style({opacity: 0, transform: 'translateX(100%)', offset: 1.0})
]))
])
]);
再在要用的地方的ts里
import { flyIn } from "../../animations/fly-in";
@Component({
...
animations: [flyIn]
})
html里
<div [@flyIn]>
我会飞 你呢
</div>
2. 主动触发动画
根据布尔值在两个状态之间切换
定义一个toggle.ts
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';
export const toggle = trigger('toggle', [
state('in', style({ opacity: '1'})),
state('out', style({ opacity: '0'})),
transition('in => out',
animate(1000, keyframes([
style({ opacity: '1'}),
style({ opacity : '0'})
]))
),
transition('out => in',
animate(1000, keyframes([
style({ opacity : '0' }),
style({ opacity : '1' })
])))
]);
主ts里面引用
import { toggle } from "../../../animations/fly-toggle";
@Component({
selector: '...',
templateUrl: '...',
styleUrls: ['...'],
animations: [toggle]
})
export class Deep {
isActive: boolean;
changeState() {
this.isActive = !this.isActive;
}
}
html里
<button (click)="changeState()">修改状态</button>
<div [@flyToggle]="isActive ? 'in' : 'out'">
</div>
<div [@flyToggle]="isActive ? 'out' : 'in'">
</div>
点击按钮触发 changeState()函数,函数里再进行运算给 isActive赋值,传回 [@flyToggle]中触发动画效果。
**
<div [@flyToggle]="isActive ? 'in' : 'out'"
(@expandState.start)="transitionStart($event)" (@expandState.done)="transitionDone($event)" >
</div>
@triggerName.start动画开始事件,@triggerName.done动画结束事件。
$event事件包含6个参数:
- fromState: 动画初始状态
- toState: 动画过渡状态
- totalTime: 过渡时间
- phaseName: 事件start或done
- element: 过渡元素
- triggerName: 过渡动画名称
3. 触发一个动画只有一个状态
有个动画 flyIn和布尔值 showAnimation
ts
...
[flyIn]
...
private showAnimation : boolean = false;
...
// 在某个情况下改变布尔值开始动画
this.showAnimation = true;
html
<div [flyIn] *ngIf='showAnimation'>
开始动画
</div>
4. * 用法
“*” 代表其自适应到本来的数值 比如说我的width为80%,给它写一个动画
import { trigger, state, animate, transition, style, keyframes } from '@angular/animations';
export const autoWidth = trigger('autoWidth', [
transition('void => *', [
animate(1000, keyframes([
style({
width: 0
}),
style({
width: '*'
})
]))
])
])
它就可以自动从width为0 在1s内到 80%的宽度,而不是原宽度的 80%。
更多用法更新于 github