Shota
Shota

Reputation: 7330

Angular 5 - Get current time of video

I have HTML5 video in my component and want to get the current video time, while it is playing.

Here is what I've tried and it only gets the time once initially.

Component TS:

export class RegisterComponent implements OnInit, OnChanges {

  @ViewChild('videoPlayer')
  private videoPlayer: ElementRef;

  constructor() { }

  ngOnInit() {
    // only logs once
    console.log(this.videoPlayer.nativeElement.currentTime);
  }

  ngOnChanges() {
    // only logs once
    console.log(this.videoPlayer.nativeElement.currentTime);
  }
}

Component HTML:

<video #videoPlayer [autoplay]="true" class="video">
    <source src="assets/videos/temp.mp4" type="video/mp4"/>
      Browser not supported
</video>

Upvotes: 4

Views: 5811

Answers (2)

The Hungry Dictator
The Hungry Dictator

Reputation: 3484

HTML

<video [autoplay]="true" (timeupdate)="onTimeUpdate($event)" class="video">
    <source src="assets/videos/temp.mp4" type="video/mp4"/>
      Browser not supported
</video>

TS

public onTimeUpdate(value){
    console.log(value.target.currentTime);
}

Upvotes: 4

chris vietor
chris vietor

Reputation: 2060

You can bind to the timeupdate event on the video tag set a variable to the value of the currentTime property of the video element.

Component TS:

export class RegisterComponent  {

  currentTime: number;

  setCurrentTime(data) {
     this.currentTime = data.target.currentTime;
  }
}

Component HTML:

<video [autoplay]="true" (timeupdate)="setCurrentTime($event)" class="video">
    <source src="assets/videos/temp.mp4" type="video/mp4"/>
      Browser not supported
</video>

Upvotes: 6

Related Questions