我正在尝试获得一个audio
组件内的元素。起初我是用老式的方式做的:
$player: HTMLAudioElement;
...
ngOnInit() {
this.$player = document.getElementById('stream')
}
但我想做角度之路™所以我想我应该使用@ViewChild
。但它返回一个ElementRef
我必须反复钻研nativeElement
属性实际上作用于元素,但它看起来更混乱。
I would like做这样的事情:
@ViewChild('stream') $player: HTMLAudioElement;
但这是行不通的。
如果您将 setter 关联到ViewChild
,你可以初始化一个HTMLAudioElement
其中的属性,然后使用该属性:
$player: HTMLAudioElement;
@ViewChild('stream') set playerRef(ref: ElementRef<HTMLAudioElement>) {
this.$player = ref.nativeElement;
}
See 这次堆栈闪电战 https://stackblitz.com/edit/angular-vvpf28?file=src%2Fapp%2Fapp.component.ts进行演示。
访问的另一种方法ElementRef.nativeElement
不那么烦人的是定义一个返回元素的 getter 属性:
@ViewChild('stream') playerRef: ElementRef<HTMLAudioElement>;
get $player(): HTMLAudioElement {
return this.playerRef.nativeElement;
}
ngAfterViewInit() {
console.log(this.$player);
}
See 这次堆栈闪电战 https://stackblitz.com/edit/angular-yey3xe?file=src%2Fapp%2Fapp.component.ts进行演示。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)