Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?
share|improve this question
up vote 3 down vote accepted

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.

share|improve this answer
    
Thanks for your time! It works! – Hongbo Miao Nov 18 '15 at 4:45
    
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 4: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 4:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.