在Angular中,可以使用delay
方法来设置动画延迟执行。以下是一个示例代码:
在组件的HTML模板中,添加一个动画元素:
This is the animated element
在组件的CSS文件中,定义动画:
@keyframes myAnimation {
0% { opacity: 0; transform: scale(0); }
100% { opacity: 1; transform: scale(1); }
}
.myAnimation {
animation: myAnimation 1s;
}
在组件的TS文件中,设置动画延迟执行:
import { Component } 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, transform: 'scale(0)' })),
state('end', style({ opacity: 1, transform: 'scale(1)' })),
transition('start => end', [
animate('1s')
])
])
]
})
export class MyComponent {
animationState = 'start';
ngAfterViewInit() {
setTimeout(() => {
this.animationState = 'end';
}, 1000);
}
animationDone(event: any) {
console.log('Animation done');
}
}
在上述代码中,动画会延迟1秒后执行。ngAfterViewInit
方法会在组件的视图初始化完成后被调用,我们使用setTimeout
方法来将动画状态从start
改为end
,从而触发动画的执行。在动画完成后,animationDone
方法会被调用,并打印一条消息。