[英]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.