简体   繁体   中英

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
    }

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM