簡體   English   中英

角度:ViewChild音頻元素是否為HTMLAudioElement?

[英]Angular: ViewChild audio element as HTMLAudioElement?

我正在嘗試在組件內部獲取audio元素。 剛開始我是用老式的方式做的:

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

但是我想做Angular Way™,所以我想應該使用@ViewChild 但是它返回ElementRef而我不得不反復鑽入nativeElement屬性以實際對元素進行操作,這看起來更加混亂。

做這樣的事情:

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

但這是行不通的。

如果將setter與ViewChild關聯,則可以在其中初始化HTMLAudioElement屬性,然后使用該屬性:

$player: HTMLAudioElement;

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

有關演示,請參見此堆疊閃電戰


減少對ElementRef.nativeElement的訪問的另一種方法是定義一個返回該元素的getter屬性:

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

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

有關演示,請參見此堆疊閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM