HTML 5 video playback from Angular 2 Typescript

I want to start playing HTML video using TypeScript when the user clicks on the video area.

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 problem is that I get an error message stating that the play() function is not defined / exists. What could be a mistake here?

+11
source share
4 answers

The problem is that you are trying to get a link to the video element using its id . Instead, you need to use the template reference variable ( # ):

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

Read more about the template reference variable here .

Edit:

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

 @ViewChild('videoPlayer') videoplayer: ElementRef; toggleVideo(event: any) { this.videoplayer.nativeElement.play(); } 

Credits to @peeskillet for this.

+30
source

Others have already answered the basic question (you should use nativeElement ). However, since nativeElement is of type any you must "cast" it to a more specific element type (for <video> this is HTMLVideoElement ).

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

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

And, of course, this is just a compilation time - you do not convert anything, and you still get an error if the item is not really a video.

+2
source

In case you have several videos to play back and you want to use the same video tag for all videos, you can defer the call to the function that is used to play the video.

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

Here's another way to set the 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(); } 
0
source

Source: https://habr.com/ru/post/1011911/


All Articles