0

我有一个 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了?

4

1 回答 1

1

它正在发生,因为 run 方法试图在相同的更改检测周期中更改图像路径。它是从模板和组件调用的:

我已经修改了你的代码来解决这个问题,请检查下面的 stackblitz:

https://stackblitz.com/edit/angular-ivy-rupneh?file=src/app/app.component.ts

于 2021-08-15T16:27:34.423 回答