简体   繁体   中英

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

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)' }" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM