如何写替代code" document.querySelector"在2角(打字稿)? [英] How to write alternative code "document.querySelector" in Angular 2 (TypeScript)?

查看:261
本文介绍了如何写替代code" document.querySelector"在2角(打字稿)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的2角(打字稿)。我想重写低于code。

 <视频>< /视频>VAR视频= document.querySelector(视频);
video.src = URL.createObjectURL(localMediaStream);
video.play();

不过,我不知道有什么办法让视频,在角2。这是迄今为止我所做的。

 <视频[来源] =videoSrc>< /视频>videoSrc:字符串;
...
this.videoSrc = URL.createObjectURL(流);
//因为我不知道有什么办法让视频,
//我有什么办法可以在这里使用video.play()?


解决方案

您可以通过使用一个局部变量和视频元素的引用> @ViewChild

@Component({
  选择:我的应用,
  模板:`<视频#我的视频>< /视频>`
})
出口类应用实施AfterViewInit {  //为myVideo ==#我的视频
  @ViewChild('为myVideo')为myVideo:任意;  afterViewInit(){
    让视频= this.myVideo.nativeElement;
    video.src = URL.createObjectURL(yourBlob);
    video.play();
  }

下面是一个 plnkr 证明的情况下(的plnkr不同一点点,因为我无法加载视频,显然这是没有那么简单,而是我加载图像作为海报的视频标签,你会得到的想法的)

更新

您删除了自己最后的评论,但它是一个有效的问题,因为的文档只能用指定方式之一 @ViewChild .The文档使用类型来查询孩子,但你也可以使用一个字符串。请参阅 ViewChildMetadata#L327 它接受一个类型(分量/指令)或一个字符串。

更新2

事实上的文档显示这个替代方案,但它在它的另一部分。在 查询 文档,你可以看到它。需要注意的是查询是pcated德$ P $,但语法仍然是有效的 ViewChild / ViewChildren ContentChild / ContentChildren

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?

解决方案

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.

这篇关于如何写替代code&QUOT; document.querySelector&QUOT;在2角(打字稿)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆