Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write alternative code "document.querySelector" in Angular 2 (TypeScript)?

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?
like image 819
Hongbo Miao Avatar asked Nov 18 '15 02:11

Hongbo Miao


People also ask

How do you use document querySelector in TypeScript?

To use the querySelector() method in TypeScript: Use a type assertion to type the selected element correctly. Use a type guard to make sure the variable does not store a null value. Access any element-specific properties.

How do you document querySelector?

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

What is querySelector in angular?

querySelector() The querySelector() method of the Element interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.

What can I use instead of document querySelector?

The other alternative is element. query / queryAll . These are alternative methods to querySelector and querySelectorAll that exist on DOM parent nodes. They also take selectors, except these selectors are interpreted relative to the element being queried from.


1 Answers

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.

like image 66
Eric Martinez Avatar answered Sep 17 '22 00:09

Eric Martinez