gpt4 book ai didi

Angular:ViewChild 音频元素作为 HTMLAudioElement?

转载 作者:行者123 更新时间:2023-12-03 20:28:48 27 4
gpt4 key购买 nike

我正在尝试获取 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;
}
this stackblitz用于演示。

访问 ElementRef.nativeElement 的另一种方法不那么烦人的是定义一个返回元素的 getter 属性:
@ViewChild('stream') playerRef: ElementRef<HTMLAudioElement>;

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

ngAfterViewInit() {
console.log(this.$player);
}
this stackblitz用于演示。

关于Angular:ViewChild 音频元素作为 HTMLAudioElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54814092/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com