Playing HTML 5 video from Angular 2 Typescript

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="https://stackoverflow.com/questions/40360174/{{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.

Leave a Comment

tech