Dre Jackson
Dre Jackson

Reputation: 771

Can not read property 'play' of null

So, what i'm trying to do is create a custom audio player. Simple enough right? That's what I thought, but then I'm getting this error "can not read property 'play' of null". I was reading about it, and I learned that one of the possibilities could be that the function is being called before the ID exist? but to me, that doesn't make sense since when a person clicks play, the property does exist. I've never created a custom audio player before so I could be way wrong here, but I would like to know how I can get this working. I'd like to play a song at the click of a button. Here is what I have so far

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "app";
  audioPlayer = <HTMLMediaElement>document.getElementById("myAudio");

  constructor() {}

  ngOnInIt() {}

  start() {
    this.audioPlayer.play();
  }
}

app.component.html

<div class="container-fluid">
  <div class="row row1">
    <div class="col-sm-12 col-md-12 col-lg-12 text-center mb-3">
      <img src="../assets/tour.jpg" class="img-fluid" />
    </div>
  </div>
  <div class="row">
    <div class="col-sm-12 col-md-12 col-lg-12 text-center">
      <p class="audio-title">Dark Queen - Lil Uzi vert</p>
      <button class="btn btn-success" id="play" (click)="start()">play</button>
      <button class="btn btn-primary" id="pause">pause</button>
      <audio id="myAudio" class="audio" controls>
        <source src="../assets/darkqueen.mp3" type="audio/mpeg" />
      </audio>
    </div>
  </div>
</div>

Uncaught TypeError: Cannot read property 'play' of null this is the only other SO discussion I found but honestly it's different from what i'm facing.

Thanks for reading.

Upvotes: 0

Views: 4290

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71901

The template is available in the ngAfterViewInit hook. Not in the constructor or ngOnInit.

Better however would be to use @ViewChild():

<audio class="audio" controls #myAudio>
  <source src="../assets/darkqueen.mp3" type="audio/mpeg">
</audio>

export class AppComponent {
  @ViewChild('myAudio')
  audioPlayer?: ElementRef<HTMLMediaElement>;

  start() {
    if (this.audioPlayer) { // if statement needed for strict typescript
      this.audioPlayer.nativeElement.play();
    }
  }
}

Upvotes: 1

Related Questions