The Angular 5 lifecycle hook ngOnChanges is triggered just once in a child component

I am struggling with syncing a child component containing complex input (such as chart data) with the API response received in the parent component in Angular 5. I am using the @Input() decorator to pass the chart data from the parent to the child component, and I need the chart to update every time the API response changes. To achieve this, I am trying to use the ngOnChanges Lifecycle hook but encountering issues. I even attempted using a dummy input field of basic number type and incrementing it, but it did not work as expected. Below is my code implementation:

Child chart component:

export class ChartComponent implements OnInit, OnChanges {

  @Input() chartData;
  @Input() triggerChart;

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
  }

}

Parent component html:

<app-chart [chartData]="chartData" [triggerChart]="triggerChartData"></app-chart>
<input [(ngModel)]="triggerChartData" type="hidden">

Parent component:

this.chartService.getChartData(params).subscribe(res => {
  this.chartData = res;
  this.triggerChartData++;
});

PS: The ngOnChanges only triggers once when the component initializes with undefined values.

Answer №1

Big shoutout to @HoangDucNguyen for providing the solution:

this.chartService.fetchData(params).subscribe(response => {
  this.data = response;
  this.changeDetectorRef.detectChanges();
});

Don't forget to import ChangeDetectorRef from @angular/core and inject it in your constructor.

The Reasoning:
When variables are modified outside of Angular's reach (e.g., within rxJs), Angular may not recognize these changes. That's why it's necessary to manually trigger the detectChanges method in Angular.

For more information, check out the official documentation: https://angular.io/api/core/ChangeDetectorRef

Answer №2

To successfully update, it is essential to utilize changeDetectorRef.

this.cd.markForCheck();
if (!this.cd['destroyed']) {
    this.cd.detectChanges();
}

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

Remove all input fields within an HTML file using a TypeScript method implemented in an Angular 2 component

Within my Angular project, there are several input elements in the HTML file that are not enclosed within a form tag. I am looking to create a function in the TypeScript file that will clear all of these inputs. I attempted to utilize ViewChild, but it a ...

Extend the express request object with Typescript and then export the modified object

Seeking to enhance the Request object from express with custom fields using typescript. Based on this particular source, I created a file named @types/express/index.d.ts containing the following code : import { MyClass } from "../../src/MyClass" ...

Can you explain the meaning of <T = MyType>?

While exploring a TypeScript file, I stumbled upon this interface declaration: interface SelectProps<T = SelectValue> extends AbstractSelectProps { /* ... */ } I've searched through the TypeScript handbook for <T = but couldn't find an ...

Deactivating the drag feature when setting the duration of a new event in FullCalendar

Hello there! I've integrated full calendar into my Angular project and I'm facing a challenge. I want to restrict users from defining the duration of an event by holding click on an empty schedule in the weekly calendar, where each date interval ...

Angular 5's external JavaScript library

After thoroughly researching this subject, I find myself still lacking comprehension. An example may be the key to understanding. As a newcomer to Angular, my goal is to create a mathematical application for mobile using Ionic. Despite investing two weeks ...

Exploring the Angular RouterModule within a Java WAR Deployment

In my Angular 6.0.5 application, I leverage Angular's Routing feature to define paths like: http://localhost:8080/area http://localhost:8080/barn http://localhost:8080/tower During development, running the app with ng serve allows me to directly en ...

``Is there a specific location where I can access the Microsoft Azure msal sign-up feature within Angular

My current Angular version is 5.2.0 and I am struggling to find a tutorial on how to incorporate Azure MSAL for new user sign-up using a Microsoft account. If anyone has any resources or examples on how to achieve this integration without having to update ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. The content provided was considered valid. An error is thrown based on the specified pattern. However, it should als ...

tips for choosing an entire group in ng-select with Angular

I am implementing a multi-select dropdown with groups in Angular using the ng-select component. My goal is to allow users to select an entire group and have all items within that group automatically selected as well. I have been attempting to model my cod ...

Error in angular2-color-picker module: Unable to retrieve the property 'substr' from an undefined source-node in source-node.js

Error in angular2-color-picker: Issue with 'substr' property, source-node.js This error occurred when I executed: npm i --save angular2-color-picker Any suggestions on how to fix this problem? ...

Sharing Angular 2 modals across different components

My Angular 2 app consists of several components, including a modal component that I added from here. Now, I want to find a way to use the same modal across multiple components. Is it possible to have one modal open when different buttons are clicked in var ...

Unraveling NGRX: a guide to invoking factory selectors from within additional selectors

NGRX has deprecated selectors with props in version 11. The recommended method now is to create factory selectors. How can you nest selectors or call one from another and pass the state between them? Prior to the change, if we had the following two selec ...

Is it possible to link fields with varying titles in NestJS?

Currently, I am developing a NestJS application that interacts with SAP (among other external applications). Unfortunately, SAP has very specific field name requirements. In some instances, I need to send over 70 fields with names that adhere to SAP's ...

Retrieving Files from POST Request Body Using Node.js and Angular

Currently, I am developing a MEAN Stack application and facing an issue while handling a form that should allow users to upload a file upon submission. The process seems to work seamlessly on the client side; however, when I inspect the request body after ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...

How can I exhibit JSON object information in an Angular 2 dropdown menu?

CSS <!-- Custom CSS Styling for Dropdown --> <div class="row no-overflow"> <div class="col-md-1 window-pad-height no-overflow"> <m ...

Typegoose's representation of modifying data

Recently, I delved into the world of NestJS and kickstarted a sample project. To integrate MongoDB seamlessly, I opted for Typegoose. A useful online tutorial () caught my eye, illustrating how to employ abstractions with base typegoose models. Hence, my ...

When HTMLElement focus is activated, it interrupts the flow of execution

(the code presented is in TypeScript and I'm working with Angular 5, but I don't think that's the issue, so prove me wrong!) I have a basic input field that triggers events in an Angular component. (EDIT: I've added the complete compo ...

Leverage ngrx to streamline action creation for multiple feature modules

My Angular 5 application consists of multiple feature modules, each responsible for assets on specific pages and lazily loaded. src/ |--app/ |--core/ <-- core functionality here |--landing/ |--store/ |--about-us/ Each module has a top-leve ...

There seems to be an issue with the type error regarding the return of the mysql2/promise

As I delve into using the mysql2/promise library with Typescript, I've encountered a puzzling issue regarding the return type of the query method. Despite my best efforts, I can't seem to resolve an error in my code. Here is a snippet from my c ...