Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get access to an HTML video element in Angular2

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.

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?

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;

That gives me this error: EXCEPTION: No value accessor for '' in [null]

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.

like image 595
Sam Avatar asked Dec 11 '15 17:12

Sam


People also ask

What is Htmlvideoelement?

A class representing the HTML video element that plays a video in a webpage.

What is Htmlelement in angular?

Angular elements are Angular components packaged as custom elements (also called Web Components), a web standard for defining new HTML elements in a framework-agnostic way.


1 Answers

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).


This should work as well

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

and then access it using $event.target


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;
}

In your component add

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

now you can access the duration with video.duration

like image 147
Günter Zöchbauer Avatar answered Oct 02 '22 21:10

Günter Zöchbauer