在Angular Universal中,当DOM元素被替换时,CSS动画会重新启动,这可能会导致不希望的视觉效果。以下是一种解决方法,可以避免在DOM替换时重新启动CSS动画。
import { Directive, ElementRef, OnDestroy, OnInit } from '@angular/core';
@Directive({
selector: '[preserveAnimation]'
})
export class PreserveAnimationDirective implements OnInit, OnDestroy {
private animationClass: string;
constructor(private el: ElementRef) {}
ngOnInit() {
this.animationClass = this.el.nativeElement.className;
}
ngOnDestroy() {
this.el.nativeElement.className = this.animationClass;
}
}
import { PreserveAnimationDirective } from './preserve-animation.directive';
@NgModule({
declarations: [ PreserveAnimationDirective ],
// 其他模块配置
})
export class MyModule { }
通过这种方式,当DOM元素被替换时,指令会在销毁时保存当前动画类名,并在初始化时重新应用保存的类名,从而保持动画状态不变。这样,CSS动画就不会重新启动。