Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code.

Issue : Employing addEventListener to monitor a specific event on the window object. When subscribing to an observable in my component to listen for changes, the variable modifications do not take effect within the subscribe method.

myService.ts

public myValue$ = new Subject<number>();

window.addEventListener('didDeviceDisconnected', (e) => {
     ...
     this.dispatchInfo(someInfo);
});

private dispatchInfo(value: number) {
     this.myValue$.next(value);
}

public getValue(): Observable<number> {
     return this.myValue$.asObservable();
}

myComponent.ts

// Waiting for the notification
this.myValueSubscription = this.myService.getValue().subscribe(value => {
     this.myValue = value;
     alert("myValue : " + this.myValue);
})

myComponent.html

{{ myValue }}

The alert correctly displays the value, but the DOM indicates that the value is undefined. Attempts such as adding setTimeout inside the subscribe function have been unsuccessful. How can I implement the change from the subscribe method? Is it beyond the angular scope?

Answer №1

Indeed, it exists beyond the realm of Angular.

You might want to experiment with this approach:

myComponent.ts

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

......

constructor(public ngZone: NgZone)

......

this.myValueSubscription = this.myService.getValue().subscribe(value => {
    this.ngZone.run(()=> {
          this.myValue = value;
        });
})

Answer №2

After thorough investigation, I successfully tackled this issue by incorporating the ChangeDetectorRef tool to enable change detection functionality.

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

constructor(..,  private cdr: ChangeDetectorRef){}

this.myValueSubscription = this.myService.getValue().subscribe(value => {
    this.myValue = value;
    alert("myValue : " + this.myValue);

    this.cdr.detectChanges(); // <= INCLUDED
})

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

Ways to substitute the $(document).ready function?

I'm facing a problem and struggling to find a solution. Here is the JavaScript script that's causing me trouble: $(function () { $.ajaxSetup({ cache: false }); var timer = window.setTimeout(function () { $(".alert").fadeTo(10 ...

Is there a way to customize a package.json file using postinstall?

I've developed a package on npm that generates an "scss directory structure" and my goal is to include custom scripts in the package.json file located at the project's root. MY-PROJECT ├── node_modules ├── scss └── package.json ...

Using the map method in JavaScript, merge two separate arrays to create a new array

In my ReactJS project, I have created two arrays using map function. The first array is defined as follows: const hey = portfolioSectorsPie.map(sector => sector.subtotal); const hello = portfolioSectorsPie.map(sector => sector.percentage) The value ...

What is the best way to incorporate server-side rendered content from a CMS to hydrate Vue.js?

Consider this scenario: content is managed through a traditional CMS such as Joomla or Drupal content is provided by the CMS as fully rendered HTML and CSS In the Frontend React.js should be utilized for all UI interactions. Despite going over most of R ...

Have developers created an event trigger for when google maps controls finish loading?

While I am aware of the tilesloaded event, it appears that the controls load after this event. My goal is to use jQuery to retrieve the controls, but I am struggling to identify the appropriate event to listen for. ...

Renaming and destructuring of an array's length using ReactJS

I am working with a reduce function shown below: let el = scopes.reduce ((tot, {actions}) => tot + actions.length, 0); I attempted to modify it as follows, but it appears that this is not the correct approach: let el = scopes.reduce ((tot, {actions.l ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

Angular progress bar with dynamic behavior during asynchronous start and stop

Currently, I am facing an issue with the progress bar functionality while utilizing the ng-bootstrap module. The scenario involves a dropdown menu with multiple options, and my desired behavior includes: The ability to start/stop the progress bar indepen ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

Using jQuery to trigger alert only once variable has been updated

I have a question that may seem too basic, but I can't find the solution. How do I make sure that the variables are updated before triggering the alert? I've heard about using callbacks, but in this case, there are two functions and I'm not ...

What is the reason behind the for of loop breaking within an async function instead of properly awaiting the execution?

Update 2: I made changes to use setTimeOut instead, which fixed the issue. Check out the accepted answer for details on what was causing the error. The code below is now functioning properly. async function getSlices() { const imgBuffs = await sliceImg ...

Easy task tracker in Vue.js

I’m currently delving into the world of VueJS and working on a simple to-do list application. The issue I’m facing is that I can't seem to successfully pass an array to the child component responsible for displaying the list: Parent Component < ...

The Mysteries of Key Codes in JavaScript

I'm curious about the character codes used for keyboards. Recently, I came across an informative article discussing this topic. In particular, I am interested in finding out which key code to use when a user presses both the alt and down arrow keys s ...

The journey of data starting from a PHP file, moving through JavaScript, and circling back to PHP

I've encountered an interesting challenge with my PHP file and Wordpress shortcode. It all starts when the shortcode is embedded in a webpage, triggering a php function from within the file. This function executes an SQL query to extract data, then s ...

Retrieve the information from the recently completed request

When the user inputs 'id' into the text field, I want to fetch a post based on the specific id entered by the user. If no id is provided, I would like to fetch the entire array of posts and then retrieve an id from the fetched data for testing pu ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

Is there a way to prevent Chrome from highlighting text that matches the content of a `position: fixed` element?

I currently have a Toc element in my HTML with the property position: fixed. (This means it remains in place as you scroll) My goal is to prevent Chrome's Find Text feature from recognizing text within that Toc element. (Ideally using JavaScript) ...

What is the best way to showcase arrays in a JSON document?

I'm working on a basic AJAX code to show a JSON file stored locally using this HTML, but I keep getting an 'undefined' error. I'm opting for JavaScript instead of JQuery since I haven't delved into it yet; hoping my code is syntact ...

Troubles with NextJS and TailwindCSS Styling

I encountered a strange issue when I used the component separately. Here's how the code looked like: <> <Head> <title>Staycation | Home</title> <meta name="viewport" content="initial- ...