如何将 "get element by id" 翻译成打字稿

How to translate "get element by id" into typescript

我的项目使用打字稿在 Angular 8 上运行。

我正在尝试通过 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" 我不明白为什么。

添加#nameForYourRef

<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.com/edit/angular-a8jahz

您可以使用 ViewChild and ElementRef 使用模板引用变量来保持 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);
  }
}

它使用 set.

将元素引用的 nativeElement 绑定到 audioPlayer 变量

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

工作示例:Stackblitz