播放Angular 2 Typescript中的HTML 5视频

问题描述 投票:13回答:5

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

这是我的HTML代码:

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

这是我的TypeScript代码:

@ViewChild('videoPlayer') videoplayer: any;

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

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

html5 angular angular2-template
5个回答
38
投票

问题是你试图使用它的video来引用id元素。您需要使用模板引用变量(#):

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

阅读有关模板参考变量here的更多信息。

编辑:

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

@ViewChild('videoPlayer') videoplayer: ElementRef;

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

致@peeskillet的这一点。


3
投票

其他人已经回答了基本问题(你必须使用nativeElement)。但是,由于nativeElementany类型,你应该将它“转换”为更具体的元素类型(对于<video>标签,这是HTMLVideoElement)。

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

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

当然这只是编译时间 - 你没有转换任何内容,如果元素不是真正的视频,你仍然会收到错误。


1
投票

这是设置videoPlayer变量以使用HTMLVideoElement进行类型安全的另一种方法

videoPlayer: HTMLVideoElement;

@ViewChild('videoPlayer')
  set mainVideoEl(el: ElementRef) {
    this.videoPlayer = el.nativeElement;
  }

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

0
投票

如果您要播放多个视频并且想要为所有视频使用相同的视频标签,则可以延迟用于播放视频的功能调用。

setTimeout(() => {
    this.yourfunction();
}, 2000) //here delaying for two seconds, you can delay for any time.

0
投票
<div class="col-md-9" style="padding-right:0">
            <video style="width: 100%;height: fit-content;" controls="controls" #videoPlayer
                src="http://localhost:3001/api/v1.0/media/{{movieId}}/stream">
            </video>

        </div>

#videoPlayer和controls =“控件提供视频播放功能以进行更多自定义,请参阅clickhere

© www.soinside.com 2019 - 2024. All rights reserved.