我正在尝试在组件内部获取一个audio
元素。一开始我是用老式的方式做的:
$player: HTMLAudioElement;
...
ngOnInit() {
this.$player = document.getElementById('stream')
}
但是我想这样做 Angular Way™ ,所以我认为应该使用@ViewChild
。但是它返回了ElementRef
,我不得不反复钻入nativeElement
属性才能对元素进行实际操作,而且看起来更加混乱。
我会 喜欢 做这样的事情:
@ViewChild('stream') $player: HTMLAudioElement;
但这不起作用。
答案 0 :(得分:2)
如果您将设置器与ViewChild
关联,则可以在其中初始化HTMLAudioElement
属性,然后再使用该属性:
$player: HTMLAudioElement;
@ViewChild('stream') set playerRef(ref: ElementRef<HTMLAudioElement>) {
this.$player = ref.nativeElement;
}
有关演示,请参见this stackblitz。
另一种减少访问ElementRef.nativeElement
的烦恼的方法是定义一个getter属性,该属性返回元素:
@ViewChild('stream') playerRef: ElementRef<HTMLAudioElement>;
get $player(): HTMLAudioElement {
return this.playerRef.nativeElement;
}
有关演示,请参见this stackblitz。