html - 如何访问 Angular2 中的 HTML 视频元素

标签 html typescript angular

我有一个 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/

相关文章:

javascript - 使用 JQuery 获取复选框选中状态

css - 使用 CSS,当广告在源代码中最后出现时,如何将广告推送到语义结构化的 HTML5 页面上?

javascript - 使 Observables 以同步和异步方式运行的方法是什么?

css -/deep/::ng-deep 之间有什么区别?

css - 以 Angular 8 居中单个组件而不影响该组件内子元素的样式

java - 在 HTML 中格式化 java 代码以像在 IDE 中一样显示它

jquery - div 在每次回发和页面刷新后出现

javascript - 如何配置 Typescript 使其 "knows about"我的 SystemJS 路径?

javascript - 如何在 Javascript 动态创建的函数中传递参数?

Angular 为 ngFor 中的每个元素调用 ngAfterContentInit