我有一个 HTML5 <video>
Angular2 组件中的元素。我需要访问它以便在允许用户将其共享到 Twitter 之前检查持续时间。
有什么方法可以通过模型绑定(bind)或直接访问 DOM,让我可以在组件的支持类中获取此信息?
我试过使用 ng-model 绑定(bind)它,就像在组件的模板中这样:
<video controls width="250" [(ng-model)]="videoElement">
<source [src]="video" type="video/mp4" />
</video>
在组件类 (TypeScript) 中:
videoElement: HTMLVideoElement;
这给了我这个错误:EXCEPTION: No value accessor for '' in [null]
我可以通过给视频元素一个 id 并使用 document.getElementById("videoElementId")
来访问它但似乎必须有更好的方法。
最佳答案
您可以注入(inject) ElementRef
然后像这样访问元素
element.nativeElement.shadowRoot.querySelector('video').duration;
// with encapsulation: ViewEncapsulation.Native
可能还有其他 View 封装模式
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
访问持续时间
关于html - 如何访问 Angular2 中的 HTML 视频元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34229139/