【问题标题】:How can i get html5 video duration on page load with angular 4?如何使用 Angular 4 在页面加载时获得 html5 视频持续时间?
【发布时间】:2017-08-28 13:27:06
【问题描述】:

html

<video #v >
    <source src="{{video.videoUrl}}" type="video/mp4" />
 </video>

<button (click)="getDuration(v)">
  Get Duration 
</button>

<input type="range" step="0.1"  min="0" 
   max="getDuration(v)">

.ts

video = {
   videoUrl :"myvideo.mp4"
   length: null,
}

getDuration(v){
  let dur = v.duration;
  dur = dur.toFixed();

  this.video.length = dur;
  return dur;
}

我可以在按钮点击时获得视频网址,但我无法在页面加载时获得。

页面加载视频时如何获取视频时长?

另外:我尝试在ngOnInit() 中调用getDuration(v) 函数,但出现错误,因为getDuration(v) 有参数。

谢谢!

【问题讨论】:

    标签: html angular html5-video


    【解决方案1】:
    1. 您需要等到元素加载完毕。使用ngAfterViewInit() 生命周期挂钩代替ngOnInit()

    2. 使用 @ViewChild 装饰器在打字稿逻辑中使用模板中的元素引用。

    在您的情况下使用 ViewChild:

    @ViewChild('v') v;
    
    ngAfterViewInit() {
    console.log(this.v);
    }
    

    【讨论】:

    • 感谢您的回答。但我不明白如何使用 ViewChild 的东西?你能理解更多关于如何使用它的细节吗?
    • 顺便说一句,它与 ElementRef 一起工作。只想说。 @ViewChild('v') v:ElementRef;this.getDuration(this.v.nativeElement)
    猜你喜欢
    • 2012-06-27
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2011-09-16
    • 1970-01-01
    • 2015-10-15
    相关资源
    最近更新 更多