如何获得访问在Angular2一个HTML视频元素 [英] How to get access to an HTML video element in Angular2

查看:1215
本文介绍了如何获得访问在Angular2一个HTML视频元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML5 <视频> 在Angular2组件元素。我需要访问它,以便允许用户将其分享到Twitter前检查时间。

I have an HTML5 <video> element in an Angular2 component. I need access to it in order to check the duration before allowing the user to share it to Twitter.

有没有办法通过模型绑定,或直接访问DOM,我可以得到在组件的支持类这些信息?

Is there any way through model binding, or direct access to the DOM, that I can get this information in the component's backing class?

我试着用NG-模型绑定,就像这样在组件的模板:

I've tried binding it using ng-model, like this in the component's template:

<video controls width="250" [(ng-model)]="videoElement">
    <source [src]="video" type="video/mp4" />
</video>

和组件的类(打字稿):

and in the component's class (TypeScript):

videoElement: HTMLVideoElement;

这给了我这个错误:例外:任何值访问器''[空]

我能够通过只给了视频元素的ID,并使用的document.getElementById(videoElementId)来访问它,但它看起来必须有一个更好的办法

I was able to access it by just giving the video element an id and using document.getElementById("videoElementId") but it seems like there must be a better way.

推荐答案

您可以注入 ElementRef ,然后访问该元素像

You can inject the ElementRef and then access the element like

element.nativeElement.shadowRoot.querySelector('video').duration;
// with encapsulation: ViewEncapsulation.Native

和其他视图封装模式大概

and with other view encapsulation modes probably

element.nativeElement.querySelector('video').duration;

(尚未尝试过自己虽然)。

(not yet tried myself though).

这应该工作以及

<video (durationchange)="durationChangeEventHandler($event)"></video>

,然后用访问 event.target

使用(在DART code为例)指令

Using a directive (example in Dart code)

@Directive(selector: 'video')
class VideoModel {
  ElementRef _element;
  VideoModel(this._element) {
    VideoElement video = _element.nativeElement as VideoElement;
    video.onDurationChange.listen((e) => duration = video.duration);
  }

  num duration;
}

在您的组件添加

@Component(
    selector: 'my-component',
    viewProviders: const [VideoModel], 
    directives: const [VideoModel],
    templateUrl: 'my_component.html') 
class MyComponent {
    @ViewChild(VideoModel) 
    VideoModel video;
}

现在,您可以访问 video.duration

这篇关于如何获得访问在Angular2一个HTML视频元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆