Sending array data from parent to child component in Angular

I am currently utilizing the ng2-chart library and I'm trying to pass data from a parent component to a child component. The data is retrieved from an API source. However, I am facing an issue where the information is not being loaded:

export class PruebasComponent implements OnInit {

  lineChartData: ChartDataSets[];
  lineChartLabels: Label[];

Within the ngOnInit method, I'm fetching the data

ngOnInit() {
    this.loading = true;

    this.datos.getDesktopLimit().subscribe(
      res => {
        this.loading = false;
        this.data = [res];
        this.dataSource = this.data[0];
        this.barChartData = true;
        this.getFilter(this.dataSource);
      }
    )
  }

Using the getFilter() function, I am able to manipulate the data before sending it:

 getFilter(data) {

     data.sort((a, b) => a.id - b.id);
    for (let entry of data) {
      this.date.push(moment(entry.created).format('DD-MM-YYYY HH:mm'))
      this.time.push(entry.total_load_time * 0.001)
    }

    this.lineChartData =  [{ data: this.time, label: 'Time Render' }];

    this.lineChartLabels = this.date;

    this.loading = false
  }

The [datasets] attribute sends empty data

 <app-graphic [datasets]="lineChartData" [labels]="lineChartLabels"></app-graphic>

Answer №1

The issue arises when passing data to the child component before receiving and completing its transformation.

To solve this problem, consider using *ngIf in the <app-graphic> component until data retrieval and transformation are complete:

<app-graphic [datasets]="lineChartData" [labels]="lineChartLabels" *ngIf="lineChartData && lineChartLabels"></app-graphic>

Implementing *ngIf should help resolve the issue.

Answer №2

When dealing with certain external components, it is crucial to avoid sending null values if they require a list.

Instead, consider using the following:

barChartData: ChartDataSets[] = [];
barChartLabels: Label[] = [];

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

Setting up Electron to utilize TypeScript's baseUrl can be achieved by following a few simple steps

In TypeScript, there is a compiler option known as baseUrl that allows you to use non-relative paths, like: import Command from "util/Command" as opposed to: import Command from "../../../util/Command" While this works fine during compilation, TypeScri ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

My Schema contains a Sub Schema that I need to make specific updates to

This is the structure of my schema: const mongoose = require('mongoose') const MaterialListSchema = new mongoose.Schema({ nomenclature:{ type: String, required: true }, national: { type: String, requir ...

Retrieve the component's name using ReactElement.type.name

In my current project, I am working with React and Typescript. I need to retrieve the name of a functional component, which I have discovered can be accessed through the 'type' property of the component like this: component.type.name. Initially, ...

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

Use Django REST to consume an API on the server side, and then display it on the client side using Angular

I recently transitioned my Angular app that was consuming an API client-side to split into backend/frontend architecture using Django REST framework. This decision was made to enhance security by keeping API credentials hidden. The migration was successful ...

Is there a way to set up custom rules in eslint and prettier to specifically exclude the usage of 'of =>' and 'returns =>' in the decorators of a resolver? Let's find out how to implement this

Overview I am currently working with NestJS and @nestjs/graphql, using default eslint and prettier settings. However, I encountered some issues when creating a graphql resolver. Challenge Prettier is showing the following error: Replace returns with (r ...

What is the process for connecting custom transformers to a compiler host?

My custom TypeScript watcher is set up like this: const compilerHost = typescript.createWatchCompilerHost(config.fileNames, config.options, typescript.sys, undefined, reportDiagnostic) typescript.createWatchProgram(compilerHost) I am trying to integrate ...

Guide on creating a Typescript function with a strongly typed argument

I am looking to develop a function that accepts a type created using export class and imported in the traditional manner as an extension of a particular type. With a base Page class and various derived classes, I aim to have this function capable of receiv ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

Reactive Programming: Transforming an earlier value as it moves down the pipeline

In a recent project, I encountered an interesting scenario involving the execution of multiple requests in a pipe chain. This specific case revolves around the display of images within the quill text editor. The backend returns the content in the followin ...

Utilizing React-select Props Typings: A Guide

I'm currently working on creating a component that wraps the AsyncSelect, but I've run into an issue with their props having generics, and I'm not sure how to approach this. Below you'll find my code snippet: export class PipTagSelect ...

Managing middleware in tRPC: Utilizing multiple methods for a single route call?

We're currently working on a group project with a tight deadline of just a few weeks. Our team has opted to utilize the T-3 stack for this project and have chosen tRPC as the server framework. While I am familiar with express, I am finding it challeng ...

Solving Peer Dependency Dilemmas in NPM Package.json Files

I have been encountering unmet peer dependency errors in my package.json file. Whenever I see the error message UNMET PEER DEPENDENCY {package@version}, I am unsure whether to install the dependency under "dependencies" or "devDependencies". I have tried ...

Error: Angular variable is undefined when using template-driven validation

When I create a form using a template-driven approach and submit it, an error occurs stating that all form fields are undefined. The form consists of five fields, and I attempt to clear them using the reset form function. As a novice in Angular, I am uncer ...

What could be causing the Toast message to not show up in react-native-root-toast?

Incorporated react-native-root-toast into my expo project running on expo 51. Please see the code snippet below for reference: const toastColors = { 'error': { color: '#DA5C53', iconName: <WarningIcon size="5 ...

How to toggle tooltip visibility dynamically using Angular 2

I am working with elements within an ngFor loop. Some of these elements have tooltips, while others do not. I am experiencing an issue where when using the code snippet below: <div ngFor="let item of items"> <div [title]="item.title"> Ele ...

Optimal method for efficiently caching data when toggling between list view and detail view within Angular 12

In my Angular App, I have implemented two components - a list view and a details view. Users can switch between these components, both of which utilize multiple async pipes. To minimize the number of http requests to the backend, I decided to cache data u ...

Develop a Java RESTful server with an Angular 5 client that utilizes POST and PUT syntax for communication

Currently, I am in the process of learning the HTTP REST/CRUD protocol in an attempt to establish communication between a Java RESTful servlet and an Angular5 client. I have successfully implemented the GET and DELETE functionalities, however, I am encount ...