我有一个 HTML5<video>
Angular2 组件中的元素。我需要访问它,以便在允许用户将其共享到 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]
我只需为视频元素提供一个 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)