Sending asynchronous data to a child component using ngOnChanges is not effective

After following a tutorial on passing async data to Angular 2 child components, specifically using solution number 2, I attempted to implement the method as shown below:

Code snippet from parent component ts :

ngOnInit() {
    this.route.queryParams.subscribe(params => { 
   this.networkService.getAttivitaById(this.idAttivita).subscribe((att:Attivita[]) => {
          this.attivita = att[0];
        })
  }

Parent component html code:

<app-dettaglio-attivita [attivita]="attivita" [isModifica]="isModifica" [intervento]="intervento"></app-dettaglio-attivita>

And here is the relevant code in the child component:

@Input() attivita: Attivita;
[...]

ngOnChanges(changes: SimpleChanges) {
    if(changes['attivita']){
      this.initPage();
      console.log("LOADED " + this.attivita.id);
    }
  }

Upon navigating to the page, the console output is as follows:

cannot read property 'id' of undefined

This error pertains to the line

console.log("LOADED " + this.attivita.id);
, followed by:

https://i.sstatic.net/QRbZT.png

It appears that the change event is being triggered twice. What causes these two changes? The tutorial does not address this issue. How can I prevent this error from occurring?

Answer №1

Make sure to also verify the presence of currentValue.

ngOnChanges(changes: SimpleChanges) {
    const { activity } = changes;
    if (activity && activity.currentValue) {
      this.initializePage();
      console.log("SUCCESSFULLY LOADED " + this.activity.id);
    }
}

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

What is the process for setting up a single timer in a non-singleton application service?

My goal is to send a GET request every X seconds. To achieve this, I have implemented a timer in the constructor of a service which is then injected into a component for use. I want the service (as a singleton) to handle scheduling the GET requests at regu ...

Unable to apply 3rd condition with ngClass into effect

I've been attempting to incorporate a third condition into my ngClass. Initially, I managed to get two classes working in my ngClass to change the row colors alternately. [ngClass]="{ totalrow:i%2 != 0, odd:i%2 == 0}" Now, I'm trying to introdu ...

NG0303: Unable to establish a connection with 'ngbTooltip' as it is not recognized as a valid property of 'button'

ERROR: 'NG0303: Can't bind to 'ngbTooltip' since it isn't a known property of 'button'.' Encountering this issue in my Angular 12 project when running local tests, the ngbTooltip error is present in all .spec files. ...

Steps to create a personalized loading screen using Angular

I am looking to enhance the loading screen for our angular 9 application. Currently, we are utilizing <div [ngClass]="isLoading ? 'loading' : ''> in each component along with the isloading: boolean variable. Whenever an API ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

Issue: App(...) is not rendering anything. This typically indicates that a return statement is missing in discord.js using react and typescript

I am struggling with an error while working on Discord OAuth2, Typescript, and React. I have tried to troubleshoot it myself but couldn't find a solution. Can someone please assist me? The issue involves being redirected constantly to the entered addr ...

Transfer information from my class to a specific pathway

Currently, I am in the process of developing an application using Angular 2. My goal is to be able to send data from my class to a specific route within the application. Sample Code @RouteConfig([ { name: 'Slider', ...

Troubleshooting Docker-compose, Nx, Angular issue "Received no data from localhost."

Attempting to deploy an Angular app with Nx using Docker compose has encountered a problem. docker-compose.yml : services: client: build: context: . dockerfile: Dockerfile volumes: - .:/app - /app/node_modules ports: ...

Typescript classes implementing data hydration and dehydration techniques

Exploring ways to share TypeScript classes or interfaces between a React + TS frontend and node + TS backend. Converting class instances into JSON poses a challenge as TS types are removed during compile time. Considering options for defining objects in a ...

Typescript - Promise resolves prematurely

I have been given a code with three essential parts that cannot be altered: 1. First, there is a call to the getData function, followed by printing the output. getData().then(console.log); 2. The function signature is as follows: async getData(): Promise ...

Unable to send JSON data from server to client following a successful file upload operation

I'm currently working on a project that involves NodeJS, Express, JQuery, and Typescript. The issue I'm facing is related to uploading a file from the front end, which is successful. However, I'm encountering difficulties in returning a JSON ...

Seeking assistance with sending variables to a dialog in Angular 2

Currently facing an issue where I need to pass the URL id from the previous page visited by a user to a service that can be referenced in a dialog. issuer.service.ts import { Injectable, EventEmitter } from '@angular/core'; import { Observabl ...

Break down the key:value objects into individual arrays

I'm currently working on an ionic project that involves handling an incoming array composed of key:value objects such as the one shown in the image below: https://i.stack.imgur.com/qrZiM.png My question is, can these values be separated into three d ...

How To Retrieve the Index of a Specific Row and Column in AgGrid (Angular)

Right now, I can retrieve the row data using the gridApi but I am struggling to determine the column index of the selected row. The method this.gridApi.getSelectedRows() does not provide any information about the column index. I would greatly appreciate ...

Wrapper around union function in TypeScript with generics

I'm struggling to find a solution for typing a wrapper function. My goal is to enhance a form control's onChange callback by adding a console.log. Can someone please point out what I might be overlooking? interface TextInput { type: 'Tex ...

Ts2532, The existence of the object is potentially unsafe

I am encountering an issue while trying to update a task in my project built with the MEAN stack. Although all APIs are functioning properly, I am facing an error when attempting to patch an element using the ID parameter. The error message displayed is: & ...

You are unable to define a module within an NgModule since it is not included in the current Angular compilation

Something strange is happening here as I am encountering an error message stating 'Cannot declare 'FormsModule' in an NgModule as it's not a part of the current compilation' when trying to import 'FormsModule' and 'R ...

Guide on retrieving the response value from the httpclient in Angular 6

I am utilizing HttpClient for sending requests. I have created a service to handle this. import { Injectable } from '@angular/core'; import { HttpClient, HttpParams, HttpHeaders, HttpResponse ,} from '@angular/common/http'; import {Obs ...

Troubleshooting problem with toggling Bootstrap accordion

Hello there! I'm currently using a bootstrap accordion within Angular, but I'm experiencing some issues with toggling. I've provided a reference to the stackblitz I created, but I can't seem to identify the cause of the toggling problem ...