在Angular中,可以使用Angular动画的state属性和keyframes来解决每次动作后动画重新开始的问题。以下是一个示例代码:
首先,在组件的HTML模板中使用动画定义:
Toggle
然后,在组件的CSS文件中定义动画:
.trigger {
width: 100px;
height: 100px;
background-color: red;
animation: myAnimation 1s;
}
@keyframes myAnimation {
from { opacity: 0; }
to { opacity: 1; }
}
接下来,在组件的Typescript文件中定义动画状态和切换动画状态的方法:
import { Component, OnInit } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css'],
animations: [
trigger('myAnimation', [
state('start', style({
opacity: 0
})),
state('end', style({
opacity: 1
})),
transition('start => end', [
animate('1s')
]),
transition('end => start', [
animate('0s')
])
])
]
})
export class MyComponent implements OnInit {
state: string;
ngOnInit() {
this.state = 'start';
}
toggleState() {
this.state = this.state === 'start' ? 'end' : 'start';
}
}
在上述代码中,使用了Angular的动画模块中的trigger函数来定义动画,并使用state属性来定义动画的不同状态。然后,使用transition方法来定义从一个状态到另一个状态的过渡,并使用animate方法来定义动画的持续时间。
在组件的初始化中,将state属性设置为起始状态。在toggleState方法中,根据当前状态切换到另一个状态。
这样,每次点击Toggle按钮时,动画都会从起始状态开始,并在1秒的时间内完成动画效果。