要解决Angular动画在完成后跳到不希望的值的问题,可以尝试以下方法:
animation
选项的fill
属性设置为forwards
,以保持动画完成后的最终状态。例如:import { trigger, state, style, transition, animate } from '@angular/animations';
@Component({
selector: 'app-my-component',
template: `
Animate me
`,
animations: [
trigger('myAnimation', [
state('active', style({ transform: 'scale(1)' })),
state('inactive', style({ transform: 'scale(0)' })),
transition('inactive => active', animate('500ms')),
transition('active => inactive', animate('500ms')),
]),
],
})
export class MyComponent {
state = 'inactive';
toggleState() {
this.state = this.state === 'inactive' ? 'active' : 'inactive';
}
}
animation
选项的end
回调函数,在动画完成后更新元素的样式。例如:import { trigger, state, style, transition, animate } from '@angular/animations';
@Component({
selector: 'app-my-component',
template: `
Animate me
`,
animations: [
trigger('myAnimation', [
state('active', style({ transform: 'scale(1)' })),
state('inactive', style({ transform: 'scale(0)' })),
transition('inactive => active', animate('500ms')),
transition('active => inactive', animate('500ms')),
]),
],
})
export class MyComponent {
state = 'inactive';
toggleState() {
this.state = this.state === 'inactive' ? 'active' : 'inactive';
}
onAnimationEnd(event: AnimationEvent) {
if (event.toState === 'active') {
event.element.style.transform = 'scale(1)';
} else if (event.toState === 'inactive') {
event.element.style.transform = 'scale(0)';
}
}
}
在以上示例中,[@myAnimation]
指令绑定到state
变量,并通过点击事件toggleState()
函数来切换状态。myAnimation
触发器定义了两个状态active
和inactive
,以及状态之间的过渡动画。第一个解决方法使用了animation
选项的fill
属性,使得动画完成后元素保持在最终状态。第二个解决方法通过animation
选项的end
回调函数,在动画完成后手动更新元素的样式。