The system encountered an issue while trying to access the property 'play' of null

I'm attempting to create a customized audio player, but I've encountered an error: "cannot read property 'play' of null". After some research, I discovered that this could be due to the function being called before the ID exists. However, it seems strange because the property should exist once the play button is clicked. Since this is my first time creating a custom audio player, I might be completely off track here. Can anyone help me figure out how to make this work? My goal is to have a song play when a button is clicked. Here's what I currently have:

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.

Answer №1

You can access the template in the ngAfterViewInit hook, rather than in the constructor or ngOnInit.

An alternative approach is to leverage @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) { // Necessary if following strict TypeScript rules
      this.audioPlayer.nativeElement.play();
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Iterating over chosen tags to generate an array or string

I need help creating a loop that will generate the following output: "1 dropdown1, 1 dropdown2, 2 dropdown3, 2 dropdown4, 3 dropdown5, 3 dropdown5...... " either as a string or an array. This is the code I have written so far, but I have hit a roadblock ...

Is there a way to efficiently update the CSS class attribute for all list items using just pure JavaScript?

I am looking to use pure Javascript, not jQuery, to access all elements within a <ul> list and remove the active class from every item except for the one selected in my menu. Shown below is the list: <ul id='flash-menu'> <li id=" ...

Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS. My current setup In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js Additionally, I use a plugin ...

Learning how to interpret and implement this particular syntax within JavaScript Redux Middleware can be a valuable skill

Currently, I am diving into the world of redux middleware by referring to this informative article: http://redux.js.org/docs/advanced/Middleware.html The code snippet presented below serves as an illustration of how a logging middleware works. const log ...

JavaScript Geocoding does not initiate the search process

Currently in the process of moving some Google Maps functions to a separate file. In my main file, I have a function search() that sets up a workflow with the other file included. The issue I'm facing is with the geocoder.geocode() function, which was ...

Jquery click on image causing mouse position issue (scrolling wrong element)

As a newbie to Jquery, I have encountered an issue with the click handler on an image. Every time the page is scrolled, the position seems to shift depending on how much the page has been scrolled. Is this normal? How can I obtain the relative position of ...

MUI Autocomplete causing a never-ending cycle of requests

One of the challenges I'm facing involves an Autocomplete component in my code. Here's a snippet of the code: <Autocomplete filterOptions={(x) => x} options={items} getOptionLabel= ...

The return value from the (VUEX + JEST) function is not defined

While working on a test, I ran into an issue. Despite double-checking everything, I can't seem to call the function correctly. Can anyone please assist me with this? The code in index.vue looks like this: import { shallowMount, createLocalVue } from ...

Using Apps Scripts to split a multi-value cell into individual rows

I need help dividing a cell with various values separated by "\n" using App Script. I've experimented with suggested functions but none have been successful. Below is an example of the current format and the desired result. https://i.sstatic.net ...

Test Transmission Service

Hey there, I'm currently working on writing Angular code for a component that involves an observable. However, I'm facing some issues testing the broadcast service as I keep getting an error indicating that the service is not being called. Does a ...

How can I create a dashed border for a pie chart using highcharts?

Is there a way to change the default solid border of a pie highchart to dashed? This modification is only necessary for pies without data or with negative data values. Perhaps it's possible to redraw the SVG of the border, like in this example: https: ...

Add a JavaScript file into a PHP document

I've been searching for a solution in various forums, but the main answer I found doesn't seem to work for me. As someone new to Web development, I'm attempting to create a simple JavaScript program that takes a JSON string of products and ...

Managing Angular routing: selectively updating named outlets without reloading submodules

My routing configuration currently reloads Module2 ListComponent on every routing event. However, I want to prevent the list from reloading when a user clicks on a list item within ListComponent. Specifically, when navigating from module2/route1 to module ...

What is the best way to place a div on top of another div with a smooth

I am trying to achieve a specific effect where depending on certain conditions, one div appears overlapping another div from the right side. Below is the code I have been working on: const [loggedIn, setLoggedIn] = useState<boolean>(false); const ...

Obtaining the unique identifier of a div element using AngularJS

Recently, I've assigned the id of ng-repeat as objectId, like this: <div class="mainListLabel " ng-if="profile==1" id={{obj.boeId}} ng-repeat="obj in mainList" ng-click="getEmployeeInformation(obj.boeId)">{{obj.boedisplayName}}</ ...

JavaScript button not responding to click event

Here is the initial structure that I have: <section id="content"> <div class="container participant"> <div class="row"> <div class="input-group"> <div class="input-group-prepend"> ...

Optimizing normals for unindexed BufferGeometry in Three.js

Currently, I am attempting to refine the normals of a mesh starting from an non indexed BufferGeometry. A similar query has been addressed in the past, however, the Three.js API has undergone significant changes since then and I am unable to make it work o ...

Combine two columns into a single table column using HTML/CSS and JavaScript with the help of Datatables

I utilize the DataTables library from https://datatables.net/ to create sortable and searchable tables on my website. However, my table becomes too wide due to the numerous columns it contains. I am looking for a way to condense the width by merging relate ...

JavaScript Implementation of Min Heap

Hello! I've been working on implementing a min heap in JavaScript and I have a question about the removeMin algorithm. I am using an array to store the heap internally. When percolating downwards, I am currently using the condition 2 * k <= this.si ...