角度:ViewChild音频元素是否为HTMLAudioElement?

时间:2019-02-21 18:41:15

标签: angular typescript viewchild

我正在尝试在组件内部获取一个audio元素。一开始我是用老式的方式做的:

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

但是我想这样做 Angular Way™ ,所以我认为应该使用@ViewChild。但是它返回了ElementRef,我不得不反复钻入nativeElement属性才能对元素进行实际操作,而且看起来更加混乱。

我会 喜欢 做这样的事情:

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

但这不起作用。

1 个答案:

答案 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