Hussein
Hussein

Reputation: 11

How can I access video element properties in angular2?

I cannot access the video element properties until I have played the video.

I am currently checking the video duration in ngOnInit and NaN value is being returned.

My lines of code to get duration are:

HTML:

<video src="myvid.mp4" #vid></video>

TypeScript:

    @ViewChild('vid') vid: ElementRef
    ngOnInit(){
      //vid is of type ElementRef
      this.duration = this.vid.nativeElement.duration
    }

Upvotes: 0

Views: 634

Answers (1)

Hussein
Hussein

Reputation: 11

The video's metadata is not being loaded so properties such as duration cannot be accessed until the video is played. To load the metadata, add the preload attribute of the video element with the value metadata. You should then add an event handler for the loadedmetadata event. Here are the changes I have made:

HTML

<video src="myvid.mp4" preload="metadata" (loadedmetadata)="vidProps($event)"></video>

TypeScript

@ViewChild('vid') vid: ElementRef
vidProps(event){
    this.duration = event.srcElement.duration
}

Upvotes: 1

Related Questions