How to access the audio element in Angular using ViewChild: Can it be treated as an

My goal is to include an audio element inside a component. Initially, I approached this by using traditional methods:

$player: HTMLAudioElement;
...
ngOnInit() {
  this.$player = document.getElementById('stream')
}

However, I wanted to follow The Angular Way™, so I decided to utilize @ViewChild. The only drawback is that it returns an ElementRef and requires accessing the nativeElement property multiple times to interact with the element, which can become messy.

I envisioned doing something like this:

@ViewChild('stream') $player: HTMLAudioElement;

Unfortunately, this approach did not yield the expected results.

Answer №1

When you link a setter to ViewChild, you have the ability to set up an HTMLAudioElement property within it, and then utilize that property later on:

$player: HTMLAudioElement;

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

Check out this stackblitz for a demonstration.


An alternative approach to simplify accessing the ElementRef.nativeElement is to create a getter property that returns the element:

@ViewChild('stream') playerRef: ElementRef<HTMLAudioElement>;

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

 ngAfterViewInit() {
    console.log(this.$player);
  }

See this stackblitz for a demo.

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

A Model in TypeScript

{ "title": { "de-DE": "German", "fr-FR": "French", "en-CA": "English" }, "image": "/tile.jpg", "url": "/url/to/version" } After receiving this JSON data, my model structure is as follows: export class MyModelStruct ...

RXJS - Leveraging BehaviorSubject's value property for optimal usage

I'm curious about the proper use of behaviorSubject.value. In a discussion on Stack Overflow, it was mentioned that values should ONLY be obtained through subscription. One scenario where it makes sense to me is when I need to determine the next valu ...

App-Root in Angular 2 not loading properly in ExpressJS route

As a newcomer to NodeJS and Express, I am trying to create a simple '/' route that points to Angular's default index.html file located at client/src/index.html. This file contains the app-root tag. While the '/' route successfully ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

Finding a solution to this issue in Angular will consistently result in a false outcome

Can anyone explain why I keep getting the error message "This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap" whenever I try to compare charTypeEnum with ChartType.text? ...

What is the process for implementing a pipe to establish data binding?

I've been trying to use a pipe for data binding in Angular, but it's not working as expected. Previously, I had this: [message]="enum.text" and now I want to replace enum.text with a custom pipe. Here's what I tried: [text]=" '' ...

Displaying HTML content in Angular 15

Struggling with Angular 15.2, I'm attempting to develop a component that can render valid HTML input. My initial approach involved using ElementRef and innerHTML: constructor( private readonly componentElement: ElementRef, ) {} ngOnInit(): void { ...

Can Vue instances support private computed properties?

Vue is a versatile tool that I utilize for both service classes and components. When it comes to reactive computeds, they prove to be incredibly beneficial. However, I often find myself wanting a clear way to differentiate between public interface compute ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Fixing the error "cannot call a function which is possibly undefined" in React and TypeScript

Seeking a resolution to the error "cannot invoke an object which can possibly be undefined" by utilizing react and typescript. What is the issue at hand? The problem arises when using the useContext react hook to create a variable (dialogContext) in compo ...

Halting the execution of a function if a new call is made within a 500ms timeframe

I am looking to enhance this code by implementing a feature that introduces a timer of 500ms whenever the onValueChange function is triggered. If the function is called again within those 500ms, it should restart the execution of the previous call. Code p ...

Utilize the ref attribute when working with Material UI InputLabel components

Is there a way to access the ref parameter of an InputLabel from the @material-ui/core library using TypeScript? When I attempt to do so, the following code produces an error related to ref: TS2769: No overload matches this call. export class ComboBo ...

What is the best way to handle the completion of an HTTP request in Angular 8?

This is the service provided. existWayBillByRsBillNumber(billNumber: string){ return this.http.get<boolean>(this.baseUrl + 'Common/ExistWayBillByRsBillNumber/'+billNumber); } This is how the service call is made. this.commonServic ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Setting up Typescript with React 17 and Tailwind CSS version 2.0

I'm struggling to set up TailwindCSS 2.0 with the create-react-app --template typescript configuration and encountering errors. Even after following the instructions on the official TailwindCSS website for React at https://tailwindcss.com/docs/guides/ ...

ng serve is consistently experiencing issues due to the absence of exported members

I am new to Angular and struggling with where and how to ask questions or effectively search for answers. Any guidance would be greatly appreciated. Currently, I am facing the following issue: After running npm install in my application, when I try to ru ...

Separate your HTML code and move it to a different HTML document within Angular CLI

Is there a way to extract my HTML section from the file app.compontent.ts and place it in a separate HTML document? I've tried adding the HTML code directly into the generated class app.component.ts but it doesn't seem to work. I'd also lik ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...