【问题标题】:How to write alternative code "document.querySelector" in Angular 2 (TypeScript)?如何在 Angular 2(TypeScript)中编写替代代码“document.querySelector”?
【发布时间】:2016-02-19 15:33:28
【问题描述】:

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

<video></video>

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

但是,我不知道在 Angular 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 的答案适用于这种情况,但如果有人真的需要做querySelector,我认为constructor(private el: ElementRef) { const result = this.el.nativeElement.querySelector('.myClass'); } 会比const result = document.querySelector('.myClass'); 更好,就像angular.io/guide/attribute-directives 一样,尽管angular.io/api/core/ElementRef 说“使用这个API作为最后的手段。”

标签: angular typescript


【解决方案1】:

您可以通过使用局部变量和@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 使用 @ViewChild 以来,这是一个有效的问题。文档使用该类型来查询子项,但您也可以使用字符串。在ViewChildMetadata#L327 中看到它接受类型(组件/指令)或字符串。

更新 2

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

【讨论】:

  • 嗨,埃里克。我发现的关于 ViewChild 的唯一内容是 angular.io/docs/js/latest/api/core/ViewChild-var.html。但是那里的代码看起来很不一样。我可以在其他任何地方学习 ViewChild 吗?谢谢!
  • 哈,实际上我想改变我的问题,因为在我发布 5 分钟后我无法编辑我的评论。所以我删除它并重新创建:) 再次感谢!
猜你喜欢
  • 2018-05-13
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
相关资源
最近更新 更多