Angular view not reflecting changes made to the model

Here is a straightforward Angular application I created to play audio using the JavaScript web Audio Object:

app.component.ts

export class AppComponent {
  title = 'media player';
  audio;
  currentTime: number;

  constructor() {
    this.audio = new Audio();
    this.audio.src = './Music/demo2.MP3';
    this.audio.play();
    this.currentTime = this.audio.currentTime;
  }
}

In addition, here is the code snippet from app.component.ts:

<h4>{{ currentTime }}</h4>

Although everything is functional, the view does not update when the model changes.

Answer №1

Angular automatically updates bindings on browser events by using zonejs to monkey patch certain browser events and trigger the detectChanges method for synchronization.

However, Angular does not update bindings for events from the Audio API as they are not monkey patched by zonejs. In such cases, you need to manually run change detection to update the bindings. One way to do this is by utilizing the ontimeupdate event handler of the audio API.

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

export class AppComponent {
  title = 'music player';
  audio;
  currentTime: number;

  constructor(private cd: ChangeDetectorRef ) {
  }
  ngOnInit(){
     this.audio = new Audio();
     this.audio.src = './Music/demo2.MP3';
     this.audio.play();
     //manually trigger change detection when time updates
     this.audio.ontimeupdate = (event) => {
        this.currentTime = this.audio.currentTime;
        this.cd.detectChanges();
     }
  }
}

Answer №2

One way to tackle this is by utilizing the setInterval method

export class AppComponent {
  title: string = 'media player';
  audio: Audio;
  currentTime: number;

  constructor() {
    this.audio = new Audio();
    this.audio.src = './Music/demo2.MP3';
    this.audio.play();
    this.currentTime = this.audio.currentTime;
  }
  
   ngOnInit() {
     setInterval(() => {
      this.currentTime = this.audio.currentTime;
    }, 1000);
   }
}

As per the input from @user184994, a simpler and more effective option might be to directly access audio.currentTime on the frontend.

<h4>{{ audio.currentTime }}</h4>

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

Angular 4/5 | Custom Dropdown Component

I have been working on a custom dropdown directive in Angular that I can attach to any DOM element. Below is the code for my directive: import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appDropdown]' ...

What is the most effective method for transferring data from Python (specifically Flask) to JavaScript?

Greetings and a happy new year to all! I am facing a practical issue: In my GUI, I prompt the user to enter a new document name using the prompt method when they click on the "Save As New" button. $("#btnSaveNew").on( "click", function() { va ...

Exploring the method to retrieve data on the server side through Express when it is shared by the client within a put request

Here is the angular http put request I am working with: sendPutRequest(data) : Observable<any>{ return this.http.put("http://localhost:5050", data).pipe(map(this.handleData)); } After making this call, the server side method being invoked is ...

Issue with jQuery Master-Detail dropdown list selection

Having trouble isolating the code in this jsfiddle script. Despite my efforts, it seems that isolation is not working as expected and Firebug isn't showing any errors on the console: <!DOCTYPE html> <html lang="en"> <head> ...

Guide to Re-rendering a component inside the +layout.svelte

Can you provide guidance on how to update a component in +layout.svelte whenever the userType changes? I would like to toggle between a login and logout state in my navbar, where the state is dependent on currentUserType. I have a store for currentUserTyp ...

What is the most effective method for refreshing a control following an Ajax request?

I am currently working on a website that sends an Ajax request to save data to a database. I would like to update the webpage to show the user that their changes have been successfully submitted. I have brainstormed three possible solutions: Immediately ...

An error of type TypeError has been encountered due to an invalid argument type. This occurred in the file located at {mypath}Desktop eddit ode_modules@redisclientdistlibclientRESP2encoder.js on line

Currently, I am diving into Ben's TypeScript GraphQL Redis tutorial for the first time. As a newcomer to TypeScript, I decided to give Redis a shot. However, when I added the property req.session.userId= user.id;, things took a turn. An error popped ...

Testing the angular components for material chips with input to ensure accurate functionality

I am currently facing an issue while trying to set up a unit test for the mat-chips element. The error message I am encountering is: "Can't bind to 'matChipInputFor' since it isn't a known property of 'input'." It seems that t ...

Arranging images next to each other using CSS and HTML

I've been trying to arrange four images side by side, with two on the top row and two on the bottom. I want to ensure they stay consistent across all browser sizes except for mobile. Here is what I have attempted so far: #imageone{ position: absol ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...

Is there a way to resolve the issue of retrieving the processed value directly in NestJS's @OnEvent function?

Due to excessive logic in the API and its slow performance, I have resorted to handling some of the logic with @OnEvent. The problem arises when the frontend runs the @GET API immediately after this API, potentially without waiting for @OnEvent to update. ...

Using Express.js to transform req.body into a POST encoded string

I need to convert the req.body object into a POST encoded string using the express.bodyParser middleware. Is there a way to achieve this? For example: Name: Jane Doe Age: 30 City: Los Angeles Should become: Name=Jane+Doe&Age=30&City=Los+Angeles ...

Security Vulnerability in Ajax Callback Breakpoints

Imagine I have the following code snippet (partially pseudocode) $.ajax({ url: "/api/user", success: function(resp) { var data = JSON(resp) if (data.user.is_admin) // do admin thing else // do somet ...

An issue detected in the index.esm.js file located in the firebase/firestore module within the node

I've encountered an issue while starting my angular project using the npm-start command. Here is the error I came across: ERROR in ./node_modules/firebase/firestore/dist/index.esm.js Module not found: Error: Can't resolve '@firebase/firest ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...

Can TypeScript React apps be styled using a style.ts file?

Exploring the world of TypeScript and encountering a new challenge - I've been tasked with styling my app using a style.ts file. Are you wondering if this is possible or how to go about it? Seeking a comprehensive answer on the feasibility of this app ...

The output from the Moment.js HTTP server is currently experiencing errors and is not displaying the expected

My first time working with JavaScript and the Momentjs library has not been smooth sailing. I am facing an issue where the output is not displaying as required. The goal is to show dates in the format "Day, date month year" (e.g., Tuesday, 14th May 2018). ...

What is the best way to integrate a loop in JavaScript to retrieve values?

<script> var data={ Data: { name: 'aaaa', number: '0003' }, values: { val: '-20.00', rate: '22047' }, user: [ '6|1|5', '10|1|15' ] }; ...

Utilizing a Firebase function with Angular

I created the following function: retrieveLikedProperties(): AngularFirestoreCollection<any> { return this.afs.collection('users', ref => ref.where('uid', '==', this._auth.currentUserId) .where(&a ...

Implementing a feature in React where the active class is applied only to the next element upon clicking

I'm just starting out with React and working on a custom menu bar project. The Mobile menu includes 2 dropdown submenus, which I want to toggle open and close by clicking an arrow. Currently, the arrows are functioning, but when I click on one arrow, ...