从 Angular 2 Typescript 播放 HTML 5 视频 [英] Playing HTML 5 video from Angular 2 Typescript

查看:22
本文介绍了从 Angular 2 Typescript 播放 HTML 5 视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的 HTML 代码:

<视频控件(点击)="toggleVideo()" id="videoPlayer"><source src="{{videoSource}}" type="video/mp4"/>浏览器不支持</视频>

这是我的 TypeScript 代码:

@ViewChild('videoPlayer') 视频播放器:任意;切换视频(事件:任何){this.videoplayer.play();}

问题是我收到一个错误,指出 play() 函数未定义/存在.这里可能有什么错误?

解决方案

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

<视频控件(点击)="toggleVideo()" #videoPlayer><source src="{{videoSource}}" type="video/mp4"/>浏览器不支持</视频>

此处阅读有关模板参考变量的更多信息.

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

@ViewChild('videoPlayer') 视频播放器:ElementRef;切换视频(事件:任何){this.videoplayer.nativeElement.play();}

感谢@peeskillet 为这个人服务.

I want to start playing a HTML video programmatically from TypeScript when the User clicks on the Video area itself.

This is my HTML code:

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

This is my TypeScript code:

@ViewChild('videoPlayer') videoplayer: any;

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

The issue is that I get an error that says play() function is not defined/exists. What could be the mistake here?

解决方案

Problem is you're trying to get a reference to video element using its id. You need to use template reference variable (#) instead:

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

Read more about template reference variable here.

Edit:

Also, in your toggleVideo(event: any) function, you need to get nativeElement and then call the play() function because you are accessing DOM element directly:

@ViewChild('videoPlayer') videoplayer: ElementRef;

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

Credits to @peeskillet for this one.

这篇关于从 Angular 2 Typescript 播放 HTML 5 视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆