The user interface in Angular 7 does not reflect the updated values after subscribing

Upon examining the code provided, it is evident that the UI does not reflect the updated value even though the field is set correctly.

I have attempted two different approaches but have not explored the change detection approach as I believe the current code should suffice.

In my service, I monitor the route end event because there are certain changes needed in the service based on whether a parameter exists in the route, such as '/page/:id'.

In one scenario, the URL could be /page and in another /page/12. Therefore, depending on this factor, I need to retrieve values from two different services – using SERVICE1 if the ID does not exist and SERVICE2 otherwise.

I have a subscribe function that returns a value from another subscribe. To achieve this, I rely on emitting the value from the inner subscribe, which works fine according to the examples below. However, the issue lies in the fact that the UI fails to render these values.

MAIN SERVICE

Note: The complete class has been omitted for brevity, only showcasing the relevant method:

  get getCourse(): Observable<CoursesDTO> {
    let subject = new Subject<CoursesDTO>();

    this.router.events.pipe(filter(e => e instanceof NavigationEnd))
      .subscribe(x => {       

        let course: CoursesDTO = {
          courseName: '',
          courseId: ''
        };

        const route = this.router.routerState.snapshot.root;

        let courseId: string = '';

        if (route.children.length >= 1) {
          const obj = route.children[route.children.length - 1];
          const value = (obj.params as any).value;

          if (!_.isEmpty(value)) {
            this.courseWorkflowProxy.interact(value.courseId, 'CourseMaterial', null)
              .subscribe((b: InteractionResponseDTO) => {

                const x: CourseDTO = <any>b.workflowResult;

                course = {
                  courseName: x.courseName,
                  courseId: x.courseId
                };

                subject.next(course);
                subject.complete();
              });
          }          
        }

        this.coursesProxy
          .getCourseInfo()
          .subscribe(b => {

            course = {
              courseName: b.courseName,
              courseId: b.courseid
            };

            subject.next(course);
            subject.complete();
          }); 
      });

    return subject;
  }

Please note, the code has been altered for demonstration purposes rather than an actual use case.

The component WatchBlock.ts demonstrates one of the proposed fixes using ngZone:

this.whatBlockService.getCourse.subscribe((r: CourseDTO) => {
  this._ngZone.run(() => {
    this.title = r.courseName;
    this.id = r.courseId;

    console.dir({ title: this.title, id: this.id });
  });
});

Although the above code successfully retrieves the desired values, they do not reflect in the rendered HTML.

The HTML section looks like:

<div fxLayout="row" fxLayoutAlign="start center">
    <div class="ml-16">
      <label class="identi">{{id}}</label>
    </div>
  </div>

  <div class="px-8 px-mat-16">
    <span class="mat-title">{{title}}</span>
  </div>

data_returned

I also attempted using the BehaviorSubject approach without success.

I decided against utilizing the change detector route as I trust that ngZone should handle the change detection automatically given its functionality.

I am at a loss with this issue and seek guidance from experienced individuals in resolving it.

Answer №1

Contrary to popular belief, simply running code in NgZone does not guarantee that the change detector will pick up on any changes made. When a component or its parent has a ChangeDetectionStrategy.OnPush set, it only checks inputs for changes. In most cases, if you don't use zone.runOutsideAngular, there's no real need to use ngZone.run.

One workaround is to inject

private _changeDetectorRef: ChangeDetectorRef
and then call
this._changeDetectorRef.markForCheck()
within the component's subscribe callback. By using markForCheck, you manually mark the component as changed when employing the OnPush strategy. For more information, refer to the official documentation.

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

Mastering the art of utilizing Angular Material's custom-palette colors for maximum impact. Unle

I have implemented a custom material-color palette where I defined the primary and accent palettes with specific shades as shown below: $my-app-primary: mat-palette($md-lightprimary ,500,900,A700 ); $my-app-accent: mat-palette($md-lightaccent, 500,900 ...

Navigating Routes with Router in Angular 7: A Step-by-Step Guide

Within my sidebar navigation component, the sidebar.component.html file is structured as follows: <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav"> <a class="navbar-brand" href="#page-top"> <span cl ...

Overriding the 'first' attribute in PrimeNG's lazy table when implementing filtering

I encountered an issue while attempting to set up a primeNG table using query parameters. For example, when accessing , the data displayed should pertain to "Joe" and start at the 20th entry. To handle the large volume of data my backend can provide, lazy ...

Determine the presence or absence of data in an Angular Observable

Here is an example of how I am making an API call: public getAllLocations(): Observable<any> { location = https://v/locations.pipe(timeout(180000)); return location; } In my appl ...

The Angular Fire Firestore module does not include the 'FirestoreSettingsToken' in its list of exported members

When I initially compiled my project, this issue occurred. The error message displayed is as follows: Module '".../node_modules/@angular/fire/firestore/angular-fire-firestore"' has no exported member 'FirestoreSettingsToken' In my a ...

What is a way to perform pre-increment without utilizing the ++I operator?

It is my belief that the code snippet below: i += 1 or i = i + 1 does not have the same effect as ++i. Am I incorrect in this assumption? Is there an alternative method to achieve pre-increment without utilizing the ++ operator? ...

Tips on resolving the 404 path error in Angular2/TypeScript ASP.NET 4.6.1 on Visual Studio 2015

I'm facing a challenge while developing a new application using TypeScript, Angular2, and ASP.NET 4.6.1 on VS2015. Two issues have come up in the process. First problem: I keep encountering 404 errors with the include files in my index.html file. Upo ...

Angular leverages property binding to connect properties and attributes in the component template

Is there a way to use a property, such as a string, to access an attribute of an object? I was thinking of something like this: cIC -> Object with attribute nameDe language -> String with nameDe <p *ngFor="let cIC of this.customerInformati ...

Display only the clear button within the p-calendar element

I am struggling to make a Clear button appear only on the p-calendar component. myComponent.html <p-calendar value="#{property.propDate}" id="date" [showIcon]="true" [utc]='true' placeholder="{{ timePickerPlaceHolder }}" [showTrans ...

Troubleshooting Angular 6: Issues with Route Guards not functioning as expected

Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id to a page-not-found error message if not already logged in, but encountering some issues. Below are t ...

unable to call a function within Angular

To create a dynamic menu, I am utilizing primeng's menu panel. Firstly, I declare my item variable: items: MenuItem[]=[]; I have two JavaScript objects to incorporate into the menu, namely groupsItem and ejsItem. Here is their structure: groupsI ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

Using the HTTP Post method to retrieve a file object: a step-by-step guide

Is there a way to utilize a http POST request in order to retrieve a file object? Though the uploading of files to the server using the POST request seems successful and flawless, attempting to fetch the file results in an unusual response: console output ...

Cookies are not being sent by Angular 2

Currently, I am working on a project that involves frontend development using angular 2 and backend with symfony as the API. However, I am facing an issue where I need to send the PHPSESSID when making a request to symfony, but it is not happening as expec ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

Error encountered: UI-Router state's 'includes' property is not recognized as a valid property in the StateDeclaration type

Prior to initiating the state transition, it is necessary to validate whether the target state falls under a parent state. The MatchCriteria is as follows: this.transition.onStart({ to: function(state) { return state.includes.parentstate; } },() = ...

Is there a way to extract information from an HttpClient Rest Api through interpolation?

I am currently facing an issue with a component in my project. The component is responsible for fetching data from a REST API using the HttpClient, and the data retrieval seems to be working fine as I can see the data being logged in the Console. However, ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

Running "npm start" does not automatically recompile or display code changes

My experience with my Angular project has been smooth until today. Surprisingly, without making any changes, the "npm start" command suddenly stopped working properly. The project compiles successfully, but any subsequent code changes do not trigger an aut ...

The Angular template-driven form featuring Material inputs will automatically reset itself when initialized

I am currently working on a simple template-based form in my application, utilizing material form fields. I have opted for this approach instead of a reactive one. The desired functionality is to display the form only when the user clicks on a button. Up ...