我<video>
在Angular2组件中有一个HTML5元素。我需要访问它以便在允许用户将其共享到Twitter之前检查持续时间。
是否可以通过模型绑定或直接访问DOM的任何方式在组件的支持类中获取此信息?
我尝试使用ng-model绑定它,就像在组件模板中这样:
<video controls width="250" [(ng-model)]="videoElement">
<source [src]="video" type="video/mp4" />
</video>
并在组件的类(TypeScript)中:
videoElement: HTMLVideoElement;
这给了我这个错误: EXCEPTION: No value accessor for '' in [null]
我可以通过给video元素一个id并使用document.getElementById("videoElementId")
它来访问它,但是似乎必须有一个更好的方法。
您可以注入ElementRef
,然后访问元素,例如
element.nativeElement.shadowRoot.querySelector('video').duration;
// with encapsulation: ViewEncapsulation.Native
以及其他视图封装模式
element.nativeElement.querySelector('video').duration;
(虽然还没有尝试过)。
这也应该工作
<video (durationchange)="durationChangeEventHandler($event)"></video>
然后使用 $event.target
使用指令(Dart代码中的示例)
@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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句