这可能是由于使用了changeDetection策略'OnPush”的组件导致的。在这种情况下,动画只会在组件输入发生更改时重新计算,并在此基础上运行。因此,如果组件未检测到输入更改,则动画将不再运行。
要解决这个问题,请确保在组件中更改了输入,以通知Angular启动动画。您可以使用RxJs的行为主题来进行此操作。例如,您可以在组件中添加以下内容:
import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core'; import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponentComponent implements OnInit {
@Input() data: any;
animationSubject = new BehaviorSubject
constructor() { }
ngOnInit() { }
ngAfterViewInit() { this.animationSubject.next(true); }
triggerAnimation() { this.animationSubject.next(false); setTimeout(() => { this.animationSubject.next(true); }, 0); } }
此代码利用了RxJs的行为主题,每次更改数据输入时都会通知更改检测。此外,在调用动画时,我们将先将主题设置为false,然后立即将其重置为true以重新计算动画。