[英]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 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;您通常应该避免从@HostListeners
返回东西,因为......除了他们收听的事件之外,它们不应该被任何东西调用;
Instead, assign window.scrollY
to a property in your component and access it from your component;相反,将window.scrollY
分配给组件中的属性并从组件中访问它;
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)' }" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.