It appears that the ChangeDetectionStrategy.OnPush is not functioning properly in the case of receiving a destructured object from a service

Implementing the OnPush strategy, a service is utilized to update some data. However, upon receiving the data in the component, it requires a click on the screen to reflect the changes.

Parent.ts
    // Click initiates the logic
    click() {
       this.showChild = true;
       setTimeout(()=> this.update, 0); // A workaround to display loading in the component until the service provides a value
    }
    update() {
    this.explorer.getData().subscribe(data => {
      this.info = {...data};
      // this.cdr.detectChanges();
    });
  }
Parent html
<app-child *ngIf="showChild" [info]="info" [otherVar]="otherVar"></app-child>

Although expecting a reference change through destructuring, the desired result is not observed. Any insights into what might be going wrong?

Answer №1

Check out a concise example I created on Stackblitz. Utilizing OnPush strategy consistently with the utilization of the Async Pipe

Parent.ts
    // Declaration of Observable Variable
    info$: Observable<InfoModel>;
    // Click initiates the logic
    click() {
       this.showChild = true;
       setTimeout(()=> this.update, 0); // Temporary solution to display loading in the component until data is received from the service
    }
    update() {
    // Instead of subscribing here, fetch only the Observable
    this.info$ = this.explorer.getData();
  }
Parent html
<!--<app-child *ngIf="showChild" [info]="info" [otherVar]="otherVar"></app-child>-->
<app-child *ngIf="showChild" [info]="info$ | async" [otherVar]="otherVar"></app-child>

Answer №2

When the reference is modified, it will initiate a change detection on a component that utilizes the OnPush change detection strategy exclusively when it corresponds to an @Input

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

Tips for tidying up the AppModule in Angular2

After following online tutorials, I managed to create a functional SPA data entry application, although it's just 'ok'. The connection to my WEB API is working fine, but as I've only built out one Model, my AppModule is already quite l ...

Navigating through different components in Angular2 is made simple with the

Struggling to create a single-page app and facing issues with routing. Despite following several tutorials, I find them quickly becoming outdated due to Angular2 still being in beta. Whenever any reference to router directives, configurations, or provider ...

Angular 4's async pipe triggers an endless loop when used in conjunction with a method call

How can I create a select UI element with dynamic options using a method that returns an observable based on the inputs provided? TypeScript (Component class) retrieveCars(type : string, engine : string) : Observable<Cars>{ return this.carServi ...

How to automatically scroll to the most recently added element in an *ngFor loop using Angular 2

In my web page, I have a dynamic list rendered using an ngFor loop. Users can add or remove elements from this list by clicking on a button. What I want to achieve is to automatically scroll the browser view to the latest element added when a user clicks o ...

Capture the keyboard event for the delete button in Angular 2

I am dealing with multiple records displayed in a gridview and need to select and delete them simultaneously. Once the records are selected, I aim to remove them in one go. Does anyone have a solution on how to trigger the delete event in angular2 when t ...

Upgrade from Next.js version 12

Greetings to all! I have recently been assigned the task of migrating a project from next.js version 12 to the latest version. The changes in page routing and app routing are posing some challenges for me as I attempt to migrate the entire website. Is ther ...

After pushing to history in React, the rendered component fails to display on the screen

I am in the process of developing a React application. Here are the dependencies I am currently using: "react": "^17.0.2", "react-dom": "^17.0.2", "react-helmet": "^6.1.0", "react-router" ...

Trying to Grasp the Concept of Angular Bootstrap AutoComplete

I am trying to make sense of this code snippet. Within the code at line 44, there is something like search = (text$: Observable) => When I hover over 'search', Intellisense indicates (property) of NgbdTypeaheadHttp.search I'm confused ...

Leverage zone.js in node.js environment without Angular framework

I am trying to implement zone.js in my Node application. Despite finding a post that explains how to do it, I keep encountering the 'zone is not defined' error. For instance, I came across an example like this: let zone = require('zone&ap ...

Implement a conditional block in my form validation process

Greetings, I have hit a roadblock with this issue for the past few days Here's the problem: I have an input field where I need to display a message based on certain conditions. One condition specifies that if it is a multiline text, use a textarea; o ...

Tips for making Angular automatically generate the property in HTML when employing the bind feature

When using property binding in Angular, I noticed that the property is not created in the HTML unless I directly write the value in the code. For example, in a StackBlitz demonstration with a 'button' component that changes color based on the typ ...

Determine whether an array is void, then proceed to deactivate a button

I am attempting to prevent a button from being clickable if an array is empty, but I am encountering difficulties. <button [disabled]="(users.length ==0 )?true:false">Send mass emails</button> Within the TypeScript file: users: UsersModel[]; ...

The execution of the start script has encountered an error

Angular: 5.0.1 / Angular CLI: 1.5.0 / Node: 8.9.1 / npm: 5.5.1 / Os: win32 x64 Executed "npm start" in the terminal/command prompt and encountered the following error. I have been struggling to fix it for a whole day with no success. Can anyone assist me ...

Tips for accessing several FormGroups within an Angular Reactive Form

Wondering if there is a method in Angular Reactive to access all FormGroups on the parent component. When I set a custom component that creates a new FormGroup within its own component, it does not reflect on the parent component. Is there a way to retri ...

Combining Two Dropdown Selections to Create a Unique Name using Angular

I am facing a challenge with 2 dropdown values and input fields, where I want to combine the selected values from the dropdowns into the input field. Below is the HTML code snippet: <div class="form-group"> <label>{{l("RoomType")}}</labe ...

How can I refresh a table's data in Angular Material 2 after making edits without having to reload the entire

In my project, I utilized angular material 2 to present a table of data in the form of orders with each row representing an order. To achieve this, I created a new instance of MatTableDataSource called currentTradesData and initialized it within the ngOnIn ...

Step-by-step guide on deploying Angular Universal

Exploring Angular universal and working on understanding deployment strategies. Check out the Github repository at https://github.com/angular/universal-starter This project includes Angular 2 Universal, TypeScript 2, and Webpack 2. After running the comm ...

Encountering a Typescript error while attempting to extract state from a History object containing an enum property

My enum structure is as follows: enum values { first, second, } Within my component, I handle the history object like this: const { push, location: { state = {} } } = useHistory(); Additionally, in the same component within a useEffect hook, I have ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

how to assign a default value for a drop-down menu in Angular 6

How can I set a default value in my dropdown in Angular? <div class="form-group"> <select id="interfaceType" (ngModelChange)="onChange($event)" [(ngModel)]="interfacengmodel" #interfaceType="ngModel" name="interfaceType" class="form-cont ...