如何将 "get element by id "翻译成typescript?

问题描述 投票:0回答:2

我的项目运行在Angular 8上,使用typescript,我想通过id获取一个html音频元素,并将其存储在一个变量中。

我试图通过id获取一个html音频元素并将其存储在一个变量中,然后我想从该元素中获取持续时间并将其存储在另一个变量中。

正如在一个工作示例中所看到的,在Javascript中,这将是这样的。

HTML

<audio id="music" preload="true">
  <source src="./assets/img/hollywood.mp3">

JS

var music = document.getElementById('music'); 
var duration = music.duration;

现在我翻译成排版稿是这样的。

TS

public music = <HTMLAudioElement>document.getElementById("music");
public duration = this.music.duration;

但当我加载页面时,我得到了错误 "Uncaught (in promise).TypeError: this.music is null",我不明白为什么。TypeError: this.music is null",我不明白为什么。

javascript angular typescript html5-audio
2个回答
0
投票

你可以使用 ViewChildElementRef 使用模板引用变量来保持Angular的方式。试试下面的方法

模板

<audio #stream autoplay (play)="onPlay()">
  <source src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg">
</audio>

控制器

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app'
})
export class AppComponent {

  audioPlayer: HTMLAudioElement;

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

  onPlay() {
    console.log(this.audioPlayer.duration);
  }
}

它结合了 nativeElement 的元素引用到 audioPlayer 使用 set.

ngAfterViewInit() 不能保证访问 duration 将返回正确的值,因为音频可能还没有开始播放。在这种情况下,它将返回 null. 所以我把它绑在 play 事件获取持续时间。

工作实例。Stackblitz


0
投票

添加 #nameForYourRefer

<audio #myAudio preload="true">
  <source src="./assets/img/hollywood.mp3">
</audio>

然后在viewInit上访问你的元素

@ViewChild('myAudio') myAudioRef: ElementRef;

  ngAfterViewInit() {
    // Console log some methods to see that it is working
    console.log(
      this.myAudioRef.nativeElement.play,
      this.myAudioRef.nativeElement.pause,
    )
  }

演示。https:/stackblitz.comeditangular-a8jahz。

© www.soinside.com 2019 - 2024. All rights reserved.