从 Angular 2 Typescript 播放 HTML 5 视频

新手上路,请多包涵

当用户单击视频区域本身时,我想以编程方式从 TypeScript 开始播放 HTML 视频。

这是我的 HTML 代码:

 <div class="video">
<video controls (click)="toggleVideo()" id="videoPlayer">
    <source src="{{videoSource}}" type="video/mp4" />
    Browser not supported
</video>
</div>

这是我的打字稿代码:

 @ViewChild('videoPlayer') videoplayer: any;

toggleVideo(event: any) {
    this.videoplayer.play();
}

问题是我收到一条错误消息,提示 play() 函数未定义/存在。这里可能是什么错误?

原文由 SoundStage 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 931
2 个回答

问题是您试图使用其 id 获取对 video 元素的引用。您需要改用 模板引用变量# ):

 <div class="video">
    <video controls (click)="toggleVideo()" #videoPlayer>
        <source src="{{videoSource}}" type="video/mp4" />
        Browser not supported
    </video>
</div>

在此处 阅读有关模板引用变量的更多信息。

编辑:

此外,在您的 toggleVideo(event: any) 函数中,您需要获取 nativeElement 然后调用 play() 函数,因为您正在直接访问 DOM 元素:

 @ViewChild('videoPlayer') videoplayer: ElementRef;

toggleVideo(event: any) {
    this.videoplayer.nativeElement.play();
}

这要归功于@peeskillet。

原文由 Stefan Svrkota 发布,翻译遵循 CC BY-SA 4.0 许可协议

其他人已经回答了基本问题(您必须使用 nativeElement )。 However, since nativeElement is of type any you should ‘cast’ it to a more specific element type (for the <video> tag this is HTMLVideoElement )。

  const video: HTMLVideoElement = this.videoElement.nativeElement;
 video.play();

然后,这将为您提供所有支持的方法和属性的智能感知。

当然,这只是编译时间——你没有转换任何东西,如果元素不是真正的视频,你仍然会得到一个错误。

原文由 Simon_Weaver 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题