[英]Angular: ViewChild audio element as HTMLAudioElement?
I'm trying to get an audio
element inside a component. 我正在尝试在组件内部获取
audio
元素。 At first I was doing it the old fashioned way: 刚开始我是用老式的方式做的:
$player: HTMLAudioElement;
...
ngOnInit() {
this.$player = document.getElementById('stream')
}
But I wanted to do it The Angular Way™ so I figured I should use @ViewChild
. 但是我想做Angular Way™,所以我想应该使用
@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. 但是它返回
ElementRef
而我不得不反复钻入nativeElement
属性以实际对元素进行操作,这看起来更加混乱。
I would like to do something like this: 我愿做这样的事情:
@ViewChild('stream') $player: HTMLAudioElement;
But that doesn't work. 但这是行不通的。
If you associate a setter to ViewChild
, you can initialize an HTMLAudioElement
property in it, and use that property afterwards: 如果将setter与
ViewChild
关联,则可以在其中初始化HTMLAudioElement
属性,然后使用该属性:
$player: HTMLAudioElement;
@ViewChild('stream') set playerRef(ref: ElementRef<HTMLAudioElement>) {
this.$player = ref.nativeElement;
}
See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战 。
Another way to make the access to the ElementRef.nativeElement
less annoying is to define a getter property that returns the element: 减少对
ElementRef.nativeElement
的访问的另一种方法是定义一个返回该元素的getter属性:
@ViewChild('stream') playerRef: ElementRef<HTMLAudioElement>;
get $player(): HTMLAudioElement {
return this.playerRef.nativeElement;
}
See this stackblitz for a demo. 有关演示,请参见此堆叠闪电战 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.