14

I am using Angular 2 (TypeScript). I want to rewrite the code below.

<video></video>

var video = document.querySelector("video");
video.src = URL.createObjectURL(localMediaStream);
video.play();

However, I don't know any way to get "video" in Angular 2. This is so far what I did.

<video [src]="videoSrc"></video>

videoSrc:string;
…
this.videoSrc = URL.createObjectURL(stream);
// Since I don't know any way to get "video",
// do I have any way to use video.play() here?
Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267
  • 1
    Late comment . . . I know the answer about @ViewChild works for this case, but if someone really needed to do querySelector, I would think that ```constructor(private el: ElementRef) { const result = this.el.nativeElement.querySelector('.myClass'); }``` would be better than ```const result = document.querySelector('.myClass'); ``` as in https://angular.io/guide/attribute-directives, though https://angular.io/api/core/ElementRef says "Use this API as the last resort." – Marcus Jun 10 '20 at 17:55

1 Answers1

19

You can get a reference to the video element by using a local variable and @ViewChild

@Component({
  selector: 'my-app',
  template : `<video #my-video></video>`
})
export class App implements AfterViewInit {

  // myVideo == #my-video
  @ViewChild('myVideo') myVideo: any;

  afterViewInit() {
    let video = this.myVideo.nativeElement;
    video.src = URL.createObjectURL(yourBlob);
    video.play();
  }

Here's a plnkr demonstrating the case (the plnkr differs a little bit, since I couldn't load a video, apparently it's no that simple, instead I load an image as the poster for video tag. You'll get the idea)

Update

You deleted your last comment, but it was a valid question since the docs only specify one way of using @ViewChild.The docs use the type to query for the children, but you can also use a string. See in ViewChildMetadata#L327 that it accepts a Type (Component/Directive) or a string.

Update 2

Actually the docs show this alternative, but it's in another part of it. Under Query docs you can see it. Note that Query is deprecated, but the syntax is still valid for ViewChild/ViewChildren and ContentChild/ContentChildren.

Eric Martinez
  • 31,277
  • 9
  • 92
  • 91
  • Hi, Eric. The only thing I found about ViewChild is angular.io/docs/js/latest/api/core/ViewChild-var.html. But the code there looks so different. Any other place I can learn ViewChild? Thanks! – Hongbo Miao Nov 18 '15 at 04:53
  • 1
    Ha, actually I want to change my question, since I cannot edit my comment after 5 min I post there. So I deleted it and created again :) Thanks again! – Hongbo Miao Nov 18 '15 at 04:59