Search code examples
angularuniversalangular11

ExpressionChangedAfterItHasBeenCheckedError when using scroll event


In my website, the logo rotate when user scroll in the page.

The code is very basic :

Component

@HostListener('window:scroll', ['$event'])
scrollPos(){
  if (typeof window !== 'undefined') {
    return Math.round(window.scrollY);
  }
}

HTML

<img src="assets/logo.svg" [ngStyle]="{ transform: 'rotate(' + scrollPos() + 'deg)' }" />

However, sometimes this basic code generate this error when navigating in the website :(

 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it 
 was checked. Previous value: 'rotate(397deg)'. Current value: 'rotate(331deg)'.

How can I update my above codes in order to avoid having this error?

thank you for your support


Solution

  • You should generally avoid returning things from @HostListeners because... they're not supposed to be called by anything but the events they listen to;

    Instead, assign window.scrollY to a property in your component and access it from your component;

    public wScrollY: number = 0;
    
    @HostListener('window:scroll', ['$event'])
    scrollPos(){
      if (typeof window !== 'undefined') {
        this.wScrollY = Math.round(window.scrollY);
      }
    }
    

    Template

    <img src="assets/logo.svg" [ngStyle]="{ transform: 'rotate(' + wScrollY + 'deg)' }" />