Angular:ViewChild 音频元素作为 HTMLAudioElement? [英] Angular: ViewChild audio element as HTMLAudioElement?

查看:35
本文介绍了Angular:ViewChild 音频元素作为 HTMLAudioElement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在组件中获取一个 audio 元素.起初我是用老式的方式做的:

I'm trying to get an audio element inside a component. At first I was doing it the old fashioned way:

$player: HTMLAudioElement;
...
ngOnInit() {
  this.$player = document.getElementById('stream')
}

但我想这样做Angular Way™,所以我想我应该使用@ViewChild.但它返回一个 ElementRef 并且我必须反复钻取 nativeElement 属性以实际作用于元素,它看起来更混乱.

But I wanted to do it The Angular Way™ so I figured I should use @ViewChild. But it returns an ElementRef and I have to repeatedly drill into the nativeElement property to actually act on the element and it just seems messier.

喜欢做这样的事情:

I would like to do something like this:

@ViewChild('stream') $player: HTMLAudioElement;

但这不起作用.

推荐答案

如果将 setter 关联到 ViewChild,则可以在其中初始化一个 HTMLAudioElement 属性,并使用之后的那个属性:

If you associate a setter to ViewChild, you can initialize an HTMLAudioElement property in it, and use that property afterwards:

$player: HTMLAudioElement;

@ViewChild('stream') set playerRef(ref: ElementRef<HTMLAudioElement>) {
  this.$player = ref.nativeElement;
}

请参阅这个stackblitz演示.

另一种使访问 ElementRef.nativeElement 不那么烦人的方法是定义一个返回元素的 getter 属性:

Another way to make the access to the ElementRef.nativeElement less annoying is to define a getter property that returns the element:

@ViewChild('stream') playerRef: ElementRef<HTMLAudioElement>;

get $player(): HTMLAudioElement {
  return this.playerRef.nativeElement;
} 

 ngAfterViewInit() {
    console.log(this.$player);
  }

请参阅此堆栈闪电战演示.

这篇关于Angular:ViewChild 音频元素作为 HTMLAudioElement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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