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

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

问题描述

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

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

这是我的HTML代码:

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>

这是我的TypeScript代码:

This is my TypeScript code:

@ViewChild('videoPlayer') videoplayer: any;

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

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

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

推荐答案

问题是您正在尝试使用video元素获取对video元素的引用.您需要改用模板参考变量(#):

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.

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

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();
}

为此获得@peeskillet的积分.

Credits to @peeskillet for this one.

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

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