我有一个 Angular 应用程序,用户按下按钮并触发动画。基本上它是两张图片相互切换以创建运行错觉。
起初,当我们开始玩时,我的角色仍然是,它的图片有动画效果,但随着它的动画效果,我得到:
ExpressionChangedAfterItHasBeenCheckedError
我的html:
<img [src]="isPlaying == false ? 'https://i.ibb.co/LgqQqFn/dino-1.png' : run()"/>
<button (click)="play()">Run</button>
我的TS:
isPlaying: boolean = false;
rightFoot: boolean = true;
play() {
this.isPlaying = !this.isPlaying
setInterval(() => {this.run()}, 200);
}
run() {
this.rightFoot = !this.rightFoot;
if (this.rightFoot == false) {
return 'https://i.ibb.co/JtQm93b/dino-3.png';
} else {
return 'https://i.ibb.co/x3JdgFf/dino-4.png';
}
}
}
我的错误代码:
错误:NG0100:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。“src”的先前值:“https://i.ibb.co/JtQm93b/dino-3.png”。当前值:'https://i.ibb.co/x3JdgFf/dino-4.png'..
我知道这与变更检测有关。我已阅读有关ngZone
它如何跟踪更改的文档,setInterval()
并将其添加到我的代码中但没有成功:
play() {
this.isPlaying = !this.isPlaying
this.ngZone.run(() => {
setInterval(() => {this.run()}, 200);})
}
这是我的问题的有效 StackBlitz。我应该如何实施 ngZone 这样我就不再得到ExpressionChangedAfterItHasBeenCheckedError
了?