播放Angular 2 Typescript中的HTML 5视频

Sou*_*age 16 html5 angular2-template angular

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

这是我的HTML代码:

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

这是我的TypeScript代码:

@ViewChild('videoPlayer') videoplayer: any;

toggleVideo(event: any) {
    this.videoplayer.play();
}
Run Code Online (Sandbox Code Playgroud)

问题是我得到一个错误,表示play()函数未定义/存在.这可能是什么错误?

Ste*_*ota 43

问题是你正在尝试video使用它来获取元素的引用id.您需要使用模板引用变量(#)代替:

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

了解更多关于模板引用变量在这里.

编辑:

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

@ViewChild('videoPlayer') videoplayer: ElementRef;

toggleVideo(event: any) {
    this.videoplayer.nativeElement.play();
}
Run Code Online (Sandbox Code Playgroud)

致@peeskillet的这一点.

  • 认为这可能对这篇文章中的其他人有帮助...在toggleVideo函数内切换暂停和播放:```this.videoplayer.nativeElement.paused?this.videoplayer.nativeElement.play():this.videoplayer.nativeElement.pause();``` (4认同)
  • 我认为你需要从elementRef获取native元素.视频是标准的HTML.见[mdn](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) (3认同)
  • Chrome 已更改自动播放政策,https://developers.google.com/web/updates/2017/09/autoplay-policy-changes。要在 chrome 中工作,请在播放前将视频静音。 (2认同)

Sim*_*ver 10

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

 const video: HTMLVideoElement = this.videoElement.nativeElement;
 video.play();
Run Code Online (Sandbox Code Playgroud)

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

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

  • 感谢您指出正确的类型。重要的是要注意 HTMLVideoElement 是视频标签的 ElementRef.nativeElement 的类型。 (2认同)

bri*_*mcq 7

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

videoPlayer: HTMLVideoElement;

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

toggleVideo(event: any) {
    this.videoplayer.play();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我的 HTML 代码:

  <video controls class="video" (play)="video()" autoplay #videoPlayer>
    <source src="assets/video/movie.mp4" type="video/mp4">
    Your browser does not support the video tag.
  </video>
Run Code Online (Sandbox Code Playgroud)

这是我的 TS 代码:

  @ViewChild('videoPlayer') videoplayer: ElementRef;

  video() {
    console.log('im Play!');
    this.videoplayer?.nativeElement.play();
  }
Run Code Online (Sandbox Code Playgroud)