Error message "The function is being called from the parent but is undefined"

Although there are numerous questions on stackoverflow with accepted answers, I haven't been able to find the specific one I'm looking for.

In my scenario, I have a parent HTML file importing another HTML from it. I am fetching a list in the parent.ts and passing it to the child component. However, when I try to use the list in the child HTML, I encounter the following error:

Any assistance on this matter would be highly appreciated.

Error:

ERROR TypeError: Cannot read property '0' of undefined
    at Object.eval [as updateDirectives] (QuarterDataComponent.html:5)

dashboard.component.ts

dashboardDataList: Dashboard[];

  ngOnInit() {
      this.selectedLineId = sessionStorage.getItem("LINE_ID");
      if(this.selectedLineId === undefined || this.selectedLineId === null) {
          alert("Please select Line in 'Configuration' tab");
          this.router.navigate(['/configuration']);
      } else {
          this.populateDashboardData();
      }
  }

      populateDashboardData() {
              this.dashboardService
                  .getDashboardData(1, 101, this.fromDatetime, this.toDatetime)
                      .subscribe(dashboardDataList => this.dashboardDataList = dashboardDataList);
          }

dashboard.component.html

<div style="height:100%;">
    <app-quarter-data [dashboardDataList]="dashboardDataList"></app-quarter-data>
</div>

quarter-data.component.ts @Component({ selector: 'app-quarter-data', templateUrl: './quarter-data.component.html', styleUrls: ['./quarter-data.component.css'] }) export class QuarterDataComponent {

    @Input() dashboardDataList: Dashboard[];

  ngOnInit() {
      alert("1...");
  }

} quarter-data.component.html (Error from the code dashboardDataList[0] )

<fieldset class="scheduler-border" [ngClass]="dashboardDataList[0].isCurrentQuarter==true ? 'current-quarter-true' : 'current-quarter-false'">
                <div class="quarterTopDiv">
                    <table  class="quarterTopTable table-sm table-striped" appearance="border">
                        <thead>
                          <tr>
                            <th>Associate #</th>
                            <th>Sequence #</th>
                          </tr>
                        </thead>
                        <tbody >
                          <tr *ngFor="let installedPartView of dashboardDataList[0].installedPartViewList let index=index; let odd=odd; let even=even">
                            <td>{{installedPartView.associateId}}</td>
                            <td [tooltip]="'[' + installedPartView.productId + ']\n [' + installedPartView.partName + ']'" placement="top" show-delay="500">{{installedPartView.afOnSequenceNo}}</td>
                          </tr>
                        </tbody>
                    </table>
                </div>

</fielsdet>

dashboard.service.ts

getDashboardDataByLineAndProcess(assNo: number, processId: string, fromDatetime: string, toDatetime: string) { return this.http .get(this.serviceUrl+'defect-result-data-for-dashboard/'+ assNo+ '/' + processId+'/' + fromDatetime + '/' + toDatetime) .map(response => { const array = response.json() as Dashboard[]; return array; }) .catch((error: any) => { if (error._body) { const errorBody = JSON.parse(error._body); this.alertService.error(errorBody.message); } else { this.alertService.error(error); } return Observable.throw(error.statusText); }); }

REST Service output:

[{
    "quarter": 1,
    "isCurrentQuarter": true,
    "noOfDefects": 3,
    "target": 0,
    "lineId": null,
    "installedPartViewList": [{
        "defectResultId": 2000009918,
        "productId": "VAN GUARD",
        "partName": "AIR SHUTTLE",
        "partId": null,
        "partSerialNumber": "A1",
        "actualTimestamp": "2019-03-06T21:17:32.773+0000",
        "quarter": 1,
        "associateId": "userid    ",
        "productionDate": null,
    }, {
        "defectResultId": 2000009919,
        "productId": "SUN PH",
        "partName": "AIR SHUTTLE",
        "partId": null,
        "partSerialNumber": "A1",
        "installedPartStatus": 1,
        "measurementStatus": null,
        "actualTimestamp": "2019-03-06T21:17:32.773+0000",
        "quarter": 1,
        "associateId": "userid    ",
        "productionDate": null,
    }, {
        "defectResultId": 2000009920,
        "productId": "SUM HOS",
        "partName": "AIR SHUTTLE",
        "partId": null,
        "partSerialNumber": "A1",
        "installedPartStatus": 1,
        "measurementStatus": null,
        "actualTimestamp": "2019-03-06T21:17:32.773+0000",
        "quarter": 1,
        "associateId": "userid    ",
        "productionDate": null,
    }],
    "defectResultViewList": [{
        "defectResultId": 2000009918,
        "productId": "BOA",
    }, {
        "defectResultId": 2000009919,
        "productId": "PHONE RT",

    }, {
        "defectResultId": 2000009920,
        "productId": "SUN PH",
    }],
    "processAssociateViewList": null,
    "associateSummaryViewList": null
}, {
    "quarter": 2,
    "isCurrentQuarter": null,
    "noOfDefects": 0,
    "target": 0,
    "lineId": null,
    "installedPartViewList": [],
    "defectResultViewList": null,
    "processAssociateViewList": null,
    "associateSummaryViewList": null
}, {
    "quarter": 3,
    "isCurrentQuarter": null,
    "noOfDefects": 0,
    "target": 0,
    "lineId": null,
    "installedPartViewList": [],
    "defectResultViewList": null,
    "processAssociateViewList": null,
    "associateSummaryViewList": null
}, {
    "quarter": 4,
    "isCurrentQuarter": null,
    "noOfDefects": 0,
    "target": 0,
    "lineId": null,
    "installedPartViewList": [],
    "defectResultViewList": null,
    "processAssociateViewList": null,
    "associateSummaryViewList": null
}]

Answer №1

Rendering the template before receiving data is a common issue. To solve this, consider wrapping the child component in an <ng-container> and using an *ngIf directive to display it only when the dashboardDataList is fully resolved.

<ng-container *ngIf="dashboardDataList">
    ...
    <fieldset class="scheduler-border" [ngClass]="dashboardDataList[0].isCurrentQuarter==true ? 'current-quarter-true' : 'current-quarter-false'">
    </fielsdet>
    ...
</ng-container>

Answer №2

Here are a couple of suggestions for you: 1) Use AfterViewInit instead of ngOnInit in order to populate the child component. 2) Incorporate an *ngIf condition within the parent component.

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

Building custom fetch hooks in React TypeScript

Currently, I am in the process of developing a custom fetch hook, but it seems like there is something crucial missing in my implementation. import React, { useContext } from 'react'; import { Context } from "../components/context"; const fetch ...

The anticipated outcomes are not achieved when utilizing environmental variables in Angular 2

Is it expected that when we use ng serve --env=prod, it should work with the values set in environment.prod.ts? Well, in my experience, it doesn't seem to be working as expected as I always receive the values from environment.ts (which is the developm ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

Engaged in revisiting a previous project and stumbling upon unfamiliar code

I need help understanding the code below. It's a bit confusing to me, but I really want to understand it. reverse = [-1, 1][+!!reverse]; ...

Does Angular 8 development mode implement tree-shaking?

I am curious to know if tree-shaking occurs during Angular 8 development mode. When running the following command: ng build I understand that tree-shaking happens when I use the command below: ng build --optimization=true|false ...

Attempting to abbreviate repetitive Javascript instructions

I have this functional javascript code, but I feel like there might be a more efficient way to write it. Any suggestions on simplifying this? let searchTerm = 'Some search text'; const isMatch = entry.title.toLowerCase().includes(searchTer ...

Using Javascript to choose an option from a dropdown menu

const salesRepSelect = document.querySelector('select[name^="salesrep"]'); for (let option of salesRepSelect.options) { if (option.value === 'Bruce Jones') { option.selected = true; break; } } Can someone please ...

Trouble with setState function within constructor in ReactJS

Running the code below in React+Redux is proving to be a challenge as I keep encountering an unhandled exception 'NodeInvocationException: Cannot read property 'showText' of null TypeError: Cannot read property 'showText' of ...

The subsequent page fails to load. Issue with the pagination feature

I'm currently stuck trying to implement pagination in my task and it's not functioning as expected. My approach involved creating two buttons with click events attached, along with a data property that changes when the buttons are clicked. This ...

I am unsure as to why the installation process fails to complete when I employ Yarn

When using yarn, the installation process does not complete as expected and does not generate essential files like src folder and gitignore. It only installs node modules and the package json file. Here is the command I used: PS C:\Users\ANAS> ...

Struggling to display the default value on a <select> element using the defaultValue prop in React

My objective is to create a dropdown menu that lists all the US state names. If there is a stateName in this.props (obtained from the redux store with values like NY, KY, or an empty string), I want the dropdown to display it by default. Otherwise, I want ...

Leverage Axios in React to dynamically fetch and display real-time data

Executing an Axios get request in order to retrieve data and display it using React. export function Wareh() { const [wareh, setWareh] = useState([{}]); useEffect(() => { axios.get("http://localhost:1515/wareh").then((response) => ...

Provide personalized files according to individual preferences

I am looking to create a website that can generate a custom file based on user input. For example, if it's a story, I want the user's name to be inserted into the text where there is a designated variable for swapping, but this customization shou ...

Slider-activated Pie Chart Controller

I have successfully created a pie chart using highchart and javascript, allowing me to adjust each slice individually using a slider. However, I am facing an issue where I want the maximum value of the pie to be 100%, with the other sliders contributing to ...

Tips for creating a responsive image gallery

After completing the development of my interactive Video Gallery using only HTML and CSS, I encountered an issue with responsiveness. Whenever I resize my browser, the images go out of the frame. I am looking for a solution to make the image gallery adjust ...

Having trouble with my first Angular 2 application that is meant to print "My First Angular 2 App"?

I have created a program to display the message "My First Angular 2 App", but I am facing issues with the output. Can anyone help me identify where I might be going wrong? environment_app.component.ts import { AnotherComponent } from './anotherCompo ...

Issue experienced with Nebular's NbRoleProvider when running in a live environment

Here is my role.provider.ts: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { map } from 'rxjs/operators/map'; import { NbAuthService, NbAuthJWTToken } from '@nebular/aut ...

Troubleshooting: Angular Binding Not Displaying

The structure of my directory is as follows: -flapper-news -app.js -index.html Within app.js, I have the following code: angular.module('flapperNews', []) .controller('MainCtrl', [ '$scope', function($scope){ $scope.t ...

Guide on creating event hooks within VUE 2.0 component connections

I have successfully created two dynamic components. Now, I am looking to trigger the "logThat(someObj)" method of component-two using events: $emit/$on with the arguments being passed as shown in this code snippet: Vue.component('component-one', ...

What is the way to activate Dynamic ng-model from a controller?

I am implementing a loop in my HTML code where each iteration dynamically creates a model. Here is an example of how the loop looks: <tr ng-repeat="item in voucherItems"> <td><input type="text" ng-model="this['id-' + $index ...