Troubleshooting: Why the OnPush change detection strategy may not be

Parent.component.html

<app-child [activeUser]="activeUser"  *ngIf="eceConfirm && activeUser"></app-child>

Parent.component.ts During the initialization of the component, the getAllEmployees method is called to fetch the employee data, and the data of the 0th index is passed to the child component using @Input() activeUser.

 getAllEmployees() {
    this.service
      .getCommonEmployeesDetail(this.user["uid"], this.selectedRatingCycleId)
      .subscribe((res) => {
        this.userList = res;
        this.changeUser(this.userList[0]);
      });
  }

  changeUser(user) {
    console.log("user", user);
    this.activeUser=user;
  }

Child.component.ts

The child component is implemented with the changeDetection.Onpush strategy. Once the activeUser data is received, it triggers the changeChildUser() method to make a request and assign the fetched data to this.cycleData.

An issue encountered is 1. When attempting to display {{cycleData.Englishmarks}} in the HTML page, it does not refresh. Although checking this.cycleData in the console shows the correct value.

If you have any insights on what might be causing this issue, please feel free to share. Your input is valuable. Thank you

 @Input() activeUser: BpuData;

ngOnChanges(changes: SimpleChanges) {
this.changeChildUser();
}



changeChildUser() {
    this.chapterService.getcycle(this.activeUser).subscribe(response =>{
         this.cycleData=response;
});  
      }

Answer №1

When dealing with OnPush components, the detection only changes when there is a modification in the input.

To address this, you can manually trigger the detection by:

updateChildUser() {
    this.chapterService.fetchData(this.activeUser).subscribe(response =>{
         this.userData=response;
         this.cdr.detectChanges();
    });  
}

Alternatively, you can use the async pipe as suggested by @Maxime.

Remember to always unsubscribe on component destruction to avoid memory leaks.

Answer №2

When dealing with OnPush components, the recommended solution is to utilize markForCheck(). Although detectChanges() can also resolve the issue, it may lead to performance issues as it triggers other components within the tree.

https://angular.io/api/core/ChangeDetectorRef#markForCheck

constructor(private cd: ChangeDetectorRef) {}

this.chapterService.getcycle(this.activeUser).subscribe(response => {
  this.cycleData = response;
  this.cd.markForCheck();
});

I have created a demonstration closely related to your project.

https://stackblitz.com/edit/angular-ivy-duuj5y

If you seek a detailed explanation of the process, you can refer to this informative resource.

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

Using a structural directive in Angular 2 that accepts a String as an input

I am attempting to develop a custom structural directive using the example provided here When trying to pass a string as an input with a slight modification, I encountered an issue where the input value was returning 'undefined' when calling th ...

How to create a beautiful grid layout using @angular/flex-layout, @angular/material, and mat-card to showcase stunning images

I have created a basic layout that looks like this: Cell 0 Cell 1 Cell 2 <!-- these are not to appear in actual render __________________________________ | Image 0 | Image 1 | Image 2 | |----------| Image 1 |----------- | text here| ...

npm is unable to install a forked git repository in its current state

Attempting to install a customized version of ng2-smart-table on my application, but npm seems to be struggling with the process. I've experimented with various commands such as npm install git+http://github.com/myusername/ng2-smart-table.git npm i ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Is it possible to utilize terms such as 'calc' within the [style.width] directive?

Can I incorporate my variable into calc() within the [style.width] directive in angular? For example: <div [style.width.px]="calc(100% - myWidth)">some texts </div> ...

Tips on rotating a material-ui icon

Having trouble rotating a material-ui icon using the CSS animation property. Can anyone assist in identifying what may be causing the issue? Link to example code sandbox I'm looking for a continuously rotating icon. ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

Switching a react virtualized table from JavaScript to TypeScript can uncover some type-related challenges

I have implemented the following demo in my React project: https://codesandbox.io/s/react-virtualized-table-checbox-stackoverflow-rbl0v?fontsize=14&hidenavigation=1&theme=dark&file=/src/App.js However, I am encountering issues with the code sni ...

Guide to verifying the upcoming behavior subject data in Angular 8

I am facing an issue where I am attempting to access the next value of a BehaviorSubject in multiple components using a service. Although I can display the value in the UI using {{ interpolation }}, I am unable to see it in the console.log. Can someone hel ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

Modify the outDir of the compiled code in NativeScript

I find it frustrating that the js files are always generated next to my ts/ng files. It's really annoying, so I decided to move the compiled/transpiled js files outside of the app directory, just like in any typical Angular app. This is what I did: ...

Angular2 encountered a TypeError stating that self._el_11 is not a valid function

Looking to attach an event listener to an input field? Check out the code snippet below: <input ref-search (keyup)="search(search.value)"> Here is the corresponding search method: search(condition: string){ console.log(condition); } When ente ...

Using Angular2 moment to format a date in a specific way

Encountered an error while using the amTimeAgo pipe from angular2-moment. The error message is as follows: Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not ...

Looking to identify the type of a adorned class in Typescript?

Consider the following scenario: return function IsDefined(object: any, propertyName: string) { .... ] We then go ahead and decorate a property like this: class Test { @IsDefined() p1: String = ""; } Now, when we execute a test inside the ...

What is the best way to generate a switch statement based on an enum type that will automatically include a case for each enum member?

While Visual Studio Professional has this feature, I am unsure how to achieve it in VS Code. Take for instance the following Colors enum: enum Colors { Red, Blue, When writing a switch statement like this: function getColor(colors: Colors) { swi ...

Transferring data from two child components back to the parent component

Within my web application, I have a parent component (A) and two children components (B, C). The parent component is responsible for maintaining the basic layout of the page, which remains consistent across all layouts. However, I need to dynamically swap ...

What is the best way to export an Angular application for users who do not have access to npm

Currently, I am developing an Angular application for a school assignment. The project is complete and runs smoothly on the console. Unfortunately, our instructors lack the patience and IT expertise to install NPM and run the project via the console. Is ...

A static method written in Typescript within an abstract class for generating a new instance of the class itself

Imagine I have abstract class Foo { } class Bar1 extends Foo { constructor(someVar) { ... } } class Bar2 extends Foo { constructor(someVar) { ... } } I want to create a static method that generates an instance of the final class (all construct ...

Troubleshooting problem with @Input number in Angular 2

Here is the component in question: <component value="3"></component> This is the code for the component: private _value:number; get value(): number { return this._value; } @Input() set value(value: number) { console.log(v ...