Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing HTML 5 video from Angular 2 Typescript

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?

like image 952
SoundStage Avatar asked Nov 01 '16 12:11

SoundStage


4 Answers

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.

like image 85
Stefan Svrkota Avatar answered Oct 22 '22 22:10

Stefan Svrkota


Others have already answered the basic question (you must use 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();

This then gives you intellisense for all the supported methods and properties.

And of course this is all just compile time - you're not converting anything and you'll still get an error if the element is not really a video.

like image 33
Simon_Weaver Avatar answered Oct 22 '22 21:10

Simon_Weaver


Here's another way to set your videoPlayer variable to use HTMLVideoElement for type safety

videoPlayer: HTMLVideoElement;

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

toggleVideo(event: any) {
    this.videoplayer.play();
}
like image 7
brijmcq Avatar answered Oct 22 '22 22:10

brijmcq


This is my HTML code:

  <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>

This is my TS code:

  @ViewChild('videoPlayer') videoplayer: ElementRef;

  video() {
    console.log('im Play!');
    this.videoplayer?.nativeElement.play();
  }
like image 5
Fahimeh Ahmadi Avatar answered Oct 22 '22 22:10

Fahimeh Ahmadi