Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 : Access play and pause of html5 video tag inside component

I am new to angular2 and I have been trying to access html5 video tag inside my component. Though I used @ViewChild decorator to access the video tag, I couldn't access the play and pause functions. My player.html file is

<video id="thisVideo" #videoplayer *ngIf="openPlayer" controls autoplay="autoplay" preload="auto" [poster]="src.thumbnailUrlHighRes" width="640">
<source [src]="src.videoURL" type="video/mp4" />
<p>Your browser does not support the video tag.</p>
</video>

The video's autoplay is set to true.I need to play and pause video using spacebar and for this I have added event listener to the host component.But the problem is I can't access video tag's play and pause function inside event listener. Can someone give me some insight?

like image 498
Aeverlite Avatar asked Apr 18 '17 09:04

Aeverlite


2 Answers

This topic has already been answered, nevertheless I believe there is a cleaner way to achieve this using template reference variables and ViewChild.

In the template, you can reference your video like this, with a #:

<video controls #myVideo>
    <source src="http://my-url/video.mp4" type="video/mp4" />
    Browser not supported
</video>
<a (click)="playVideo()">Play video</a>

And in your .ts file:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})

export class MyComponent implements OnInit {
  @ViewChild('myVideo') myVideo: ElementRef; // Prior to Angular 8
  // @ViewChild('myVideo', { static: true }) myVideo: ElementRef; => Angular 8
  constructor() { }

  ngOnInit() {
  }

  playVideo() {
    /**
     * You are accessing a dom element directly here,
     * so you need to call "nativeElement" first.
     */
    this.myVideo.nativeElement.play();
  }

}
like image 198
schankam Avatar answered Oct 17 '22 07:10

schankam


I got it working with this:

@HostListener('document:keyup', ['$event'])
  onKeyUp(ev:KeyboardEvent) {
    if(ev.code == "Space") {
      let vid = <HTMLVideoElement>document.getElementById("thisVideo");
      if(vid.paused) {
        vid.play();
      }
      else {
        vid.pause();
      }
    }
  }
like image 29
Jake Avatar answered Oct 17 '22 06:10

Jake