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

I'm looking for the configuration of function definitions for the Jasmine npm module within an Angular project. Can

When a new Angular project is created, the *.spec.ts files provide access to Jasmine functions such as "describe", "beforeEach", and expect. Despite not having an import clause for them in spec.ts files, I can click on these functions and navigate to their ...

Using TypeScript to eliminate duplicate values when constructing an array with various properties

Recently, I received an array from an API that has the following structure: results = [ {name: 'Ana', country: 'US', language: 'EN'}, {name: 'Paul', country: 'UK', language: 'EN'}, {name: & ...

Returning a value with an `any` type without proper validation.eslint@typescript-eslint/no-unsafe-return

I am currently working on a project using Vue and TypeScript, and I am encountering an issue with returning a function while attempting to validate my form. Below are the errors I am facing: Element implicitly has an 'any' type because expression ...

What is the best way to manage a promise in Jest?

I am encountering an issue at this particular section of my code. The error message reads: Received promise resolved instead of rejected. I'm uncertain about how to address this problem, could someone provide assistance? it("should not create a m ...

Angular template error: 'Component' type does not have the specified property

I am facing an issue with importing an array from a file named platforms.ts. The array is declared as shown below: export const platforms: Platforms[] = [ { name: 'Instagram', value: 'instagram' }, { name: 'Facebo ...

Ways to reset an input field when focused

Looking to implement a number input field in React that clears the initial value when the user clicks on it. While there are solutions available for text inputs, I have not come across a method for number inputs. Every attempt I make at solving this issu ...

Issues with updating ngModel in Angular 4 after input changes during testing

My application consists of a simple component with just one input: @Component({ selector: 'mycomponent', styles: [ ], template: ` <div class="new-stuff"> <div> <div> Name: <input type="text ...

Typescript fetch implementation

I've been researching how to create a TypeScript wrapper for type-safe fetch calls, and I came across a helpful forum thread from 2016. However, despite attempting the suggestions provided in that thread, I am still encountering issues with my code. ...

Limiting the scope of TypeScript types to specific keys, such as Exact/DeepExact

After coming across this specific query on SO, I wanted to delve into creating an Exact type. My attempt at implementing something akin to a DeepExact seems to be close: // Desired type that should only accept Exact versions of type Opts = { firstName?: ...

Ionic 2 - Error: Module ""."" not found at runtime

Encountered a perplexing error while running my Ionic 2 application on localhost using the command: ionic serve I've diligently inspected all my imports for any incorrect paths in my TypeScript files, but haven't found anything amiss. The only ...

I am having trouble getting the bs-stepper to function properly within my Angular project

I am currently facing issues with the bs-stepper module in my Angular code. It is not functioning as expected and is throwing errors. Here is a snippet of my code: export class FileUploadProcessComponent implements OnInit { import Stepper from 'b ...

Unable to display animation without first launching it on Rive web

I attempted to incorporate a Rive animation into my Angular web application <canvas riv="checkmark_icon" width="500" height="500"> <riv-animation name="idle" [play]="animate" (load)=&qu ...

Is there a way for me to steer clear of having to rely on the Elvis Operator?

Throughout my journey building my Angular 2 website, I've found the Elvis Operator to be a crucial element that makes everything possible. It seems like every task I undertake involves mastering how to apply it correctly in every instance where data i ...

Angular displays a datalist input as "[object Object]" once a value has been selected

In my form, I have the following section: <div formArrayName="studentPublishing" *ngFor="let all of getstudentPublishing().controls; index as i"> <div class="form-group data"> <input type="text& ...

Submitting the object in the correct format for the Firebase database

My goal is to structure the Firebase database in the following way: "thumbnails": { "72": "http://url.to.72px.thumbnail", "144": "http://url.to.144px.thumbnail" } However, I am struggling to correctly set the keys '72' and '144&apos ...

Encountered an issue in GoJS with Angular 4: ERROR TypeError: Unable to access property 'class' of null at Function.F.fromJson.F.fromJSON

I have just started exploring GoJS and decided to create a sample project by utilizing the Kanban sample available on the GoJs website. I attempted to use Angular and Typescript for this, but encountered an error. AppComponent.html:1 ERROR TypeError: Cann ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

Determine the data type of an index within an array declaration

Imagine we have the following array literal: const list = ['foo', 'bar', 'baz'] as const; We are attempting to create a type that represents potential indices of this array. This is what we tried: const list = ['foo&ap ...

A guide to configuring VSCode to recognize the DefinitelyTyped global variable (grecaptcha) within a Vuejs 3 TypeScript project

I have recently set up a new project using Vue.js 3 and TypeScript by running the command npm init vue@latest. I now want to integrate reCaptcha v2 into the project from scratch, without relying on pre-existing libraries like vue3-recaptcha-v2. Instead of ...

In Production mode, Angular automatically reloads the page every time my data request service is executed to fetch data from the API

The Issue at Hand I have developed an angular application that functions flawlessly on the development server. This application utilizes localStorage to store the user's JWT token, although I am aware that this may not be the most secure method. How ...