我在angular中创建了一个动画,我需要知道它什么时候开始,所以我定义了一个回调。问题是当组件加载时,即使没有改变状态,回调也会被触发。
模板
<button (click)="click()">click</button>
<div class="myclass" [@throwBall]="state" (@throwBall.start)="animStart($event)" >
</div>
的组件。
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
animations: [
trigger('throwBall', [
state('steady', style({ })),
state('throw', style({ top: '300px' })),
transition('steady => throw', [animate('2s')])
]),
trigger('blockInitialRenderAnimation', [
transition(':enter', [])
])
]
})
export class AppComponent {
state = 'steady';
click() {
this.state = 'throw';
}
animStart(event: any) {
if (event.fromState !== 'void') {
console.log('anim start callback');
}
}
}
这里是一个演示。https:/stackblitz.comeditangular-9szgic。
为什么当组件加载时,'anim start callback'会在控制台中显示?
动画的初始状态是一个 "无状态 "的状态,叫做 void
- 当使用动画时,这是默认状态。state
变量到 steady
从没有的动画开始 void
-> steady
.
为了达到你的目标,你应该使用属性为 fromState
& toState
的 动画事件.
import { AnimationEvent, } from '@angular/animations';
public animStart(event: AnimationEvent): void {
if(event.fromState === 'steady') {
// ...
}
}
尝试登录 AnimationEvent
在你 animStart
方法,以便更好地理解这个 interface
.
public animStart(event: AnimationEvent): void {
console.log(event);
}