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

Angular集成model-viewer时Typescript报ProgressEvent无detail属性求助

解决方案

1. 直接通过类型断言修正事件类型

TypeScript默认将progress事件推断为标准ProgressEvent,但model-viewer的progress是携带数字进度值的自定义CustomEvent,可以通过类型断言明确事件类型:

modelViewerload.addEventListener('progress', (ev) => {
  // 将事件断言为包含数字类型detail的CustomEvent
  const customEvent = ev as CustomEvent<number>;
  const totalProgress1 = customEvent.detail;
  
  console.log(totalProgress1);
  progress.classList.toggle('show', totalProgress1 < 1);
  bar.style.transform = `scaleX(${totalProgress1})`;
});

也可以直接在参数声明时指定类型,写法更简洁:

modelViewerload.addEventListener('progress', (ev: CustomEvent<number>) => {
  const totalProgress1 = ev.detail;
  // 后续逻辑保持不变
});

2. 引入官方类型定义(推荐)

安装model-viewer的官方TypeScript类型包,让TypeScript自动识别组件及事件的正确类型:

执行安装命令:

npm install @types/model-viewer --save-dev

在Angular组件中,通过@ViewChild获取元素时指定正确类型,TypeScript会自动推断事件类型:

import { ViewChild, ElementRef } from '@angular/core';
import type { HTMLModelViewerElement } from 'model-viewer';

@Component({
  // 组件配置内容
})
export class YourComponent {
  @ViewChild('modelViewer') modelViewer!: ElementRef<HTMLModelViewerElement>;

  ngAfterViewInit() {
    this.modelViewer.nativeElement.addEventListener('progress', (ev) => {
      // 此时ev会被自动识别为带detail属性的CustomEvent
      const totalProgress1 = ev.detail;
      // 后续逻辑
    });
  }
}

3. 类型守卫实现严谨检查(可选)

如果需要更严谨的类型校验,可以通过运行时检查让TypeScript自动推导类型:

modelViewerload.addEventListener('progress', (ev) => {
  if ('detail' in ev && typeof ev.detail === 'number') {
    const totalProgress1 = ev.detail;
    // 后续逻辑
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:15:43