You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular:@HostListener window:scroll事件参数类型及报错解决

解决Angular监听window:scroll事件的类型报错问题

你遇到的两个报错原因如下:

  • e.target 可能为 null:TypeScript对Event.target的类型定义是EventTarget | null,存在空值风险
  • scrollingElement 不存在于EventTarget类型:scrollingElement是Window接口的专属属性,而EventTarget是更通用的父类型,不包含该属性

正确的处理方式

事件参数用Event类型本身没问题,但需要对e.target做类型断言缩小范围,或者直接使用window对象获取滚动距离(更简洁)。

方案1:类型断言修正事件目标类型

import { Component, ElementRef, HostListener, ViewChild } from '@angular/core';

@Component({
  selector: 'app-layout-topbar',
  templateUrl: './topbar.component.html',
  styleUrls: ['./topbar.component.scss'],
})
export class TopbarComponent {
  @ViewChild('topbar') topbar?: ElementRef;

  @HostListener('window:scroll', ['$event'])
  onWindowScroll(e: Event) {
    if (!this.topbar) return;
    // 将事件目标断言为Window类型,并处理可能的null情况
    const windowTarget = e.target as Window | null;
    if (!windowTarget) return;
    
    // 安全获取滚动距离,兼容不同浏览器
    const scrollTop = windowTarget.scrollingElement?.scrollTop || document.documentElement.scrollTop || 0;

    if (scrollTop > 500) {
      this.topbar.nativeElement.classList.add('sticky-topbar');
      this.topbar.nativeElement.classList.remove('hide-topbar');
    } else if (scrollTop > 10) {
      this.topbar.nativeElement.classList.add('hide-topbar');
    } else {
      this.topbar.nativeElement.classList.remove('sticky-topbar');
      this.topbar.nativeElement.classList.remove('hide-topbar');
    }
  }
}

方案2:直接使用window对象(更推荐)

因为监听的是window的滚动事件,完全可以跳过事件参数,直接访问window的滚动属性:

import { Component, ElementRef, HostListener, ViewChild } from '@angular/core';

@Component({
  selector: 'app-layout-topbar',
  templateUrl: './topbar.component.html',
  styleUrls: ['./topbar.component.scss'],
})
export class TopbarComponent {
  @ViewChild('topbar') topbar?: ElementRef;

  @HostListener('window:scroll')
  onWindowScroll() {
    if (!this.topbar) return;
    // 直接获取滚动距离,兼容多浏览器
    const scrollTop = window.scrollY || document.documentElement.scrollTop || 0;

    if (scrollTop > 500) {
      this.topbar.nativeElement.classList.add('sticky-topbar');
      this.topbar.nativeElement.classList.remove('hide-topbar');
    } else if (scrollTop > 10) {
      this.topbar.nativeElement.classList.add('hide-topbar');
    } else {
      this.topbar.nativeElement.classList.remove('sticky-topbar');
      this.topbar.nativeElement.classList.remove('hide-topbar');
    }
  }
}

补充说明

  • window.scrollY是现代浏览器标准属性,document.documentElement.scrollTop用于兼容旧版浏览器
  • 类型断言时加上| null并做空值判断,符合TypeScript严格空值检查规范

内容的提问来源于stack exchange,提问作者Matt Oliveira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:55:37