如何在 Angular 2 (TypeScript) 中编写替代代码 "document.querySelector"?

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

我正在使用 Angular 2 (TypeScript)。我想重写下面的代码。

<video></video>

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

但是,我不知道有什么方法可以在 Angular 中获得 "video" 2。到目前为止,我就是这样做的。

<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?

您可以通过使用局部变量和 @ViewChild

获取对 video 元素的引用
@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();
  }

这里有一个 plnkr 演示案例(plnkr 有点不同,因为我无法加载视频,显然没有那么简单,而是加载图像作为视频标签的海报。你会明白的)

更新

您删除了最后一条评论,但这是一个有效的问题,因为 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 它接受类型 (Component/Directive) 或字符串。

更新 2

实际上文档显示了这个替代方案,但它在它的另一部分。在 Query 文档下你可以看到它。请注意 Query 已弃用,但语法对 ViewChild/ViewChildrenContentChild/ContentChildren.

仍然有效