Unable to invoke method because ViewChild component is undefined

I am currently fetching data from a database and once the data is ready, I want to bind it to a child element using ViewChild in order to pass the object data to the child component.

The problem I'm facing is that the component is not immediately "ready," so I had to set a timeout of 2 seconds before binding.

However, this approach doesn't feel appropriate. How can I determine when the child component is actually ready?

The parent component fetches data from the DB

 @ViewChild("assumps") assumps: AssumptionsComponent
 getProposalAmounts() {
    this.targets.getProposalAmounts().subscribe((data) => {
    this.assumptions = data.assumptions;

    setTimeout(() => {
      this.assumps.setAssumptionsForm(this.assumptions);
    }, 2000)

Inside the child component

setAssumptionsForm(obj: Assumptions) {
if (obj != null) {
  this.assumptionsObj = obj;
}

If the timeout is removed, the child component is null; The error message says

Cannot read property 'setAssumptionsForm' of undefined

Thank you

Answer №1

To ensure communication between components, you could establish a service and set up a subscription to it. This way, when the child constructor is triggered, an event can be emitted to notify the parent component of its readiness.

In my opinion, this method appears to be the most effective solution.

Alternatively, you could pass data as input to the child component and implement a loading mechanism for cases where the data is not yet available.

Personally, I lean towards the first approach as it offers greater reusability in the long run :)

Answer №2

It appears that you are anticipating the assumps template to be rendered immediately upon assigning a value to this.assumptions, but it doesn't work like that. Feel free to correct me if I'm making the wrong assumptions.

Alternatively, you could create a QueryList (special Observable) of AssumptionsComponent when performing the ViewChild query. Subsequently, monitor the changes property of the QueryList Observable. This way, you'll be able to track any changes (DOM additions or removals) occurring with the #assumps template variable directly.

@ViewChild("assumps") assumps: QueryList<AssumptionsComponent>;

getProposalAmounts() {
    this.targets.getProposalAmounts().subscribe((data) => {
    this.assumptions = data.assumptions;
}

ngOnInit () {
    this.assumps.changes((list) => {
        list.forEach(assump => 
          assump.setAssumptionsForm(this.assumptions)
        )
    })        
}

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 are the steps to creating an Observable class?

I am working with a class that includes the following properties: export class Model { public id: number; public name: string; } Is there a way to make this class observable, so that changes in its properties can be listened to? I'm hoping fo ...

Button is not responding to the Ionic [clear] property

I attempted to create a transparent button using Ionic's clear attribute as suggested in the documentation. Despite following the instructions, it doesn't seem to work for me. Can you help me identify what I might be doing incorrectly? <butto ...

Can schemas be utilized within Deno development?

I have a data structure that I am looking to store and work with in Deno using MongoDB. Here is a similar example of the data format: [ { id: "AAPL", stockData: [ { date: 1634601600, summary: [Object] }, ...

Is it possible for jQuery to create a popup window displaying a specific value?

Using JavaScript, I have implemented functionality to open a child window when the user clicks on a button from the parent window. The child window contains a textbox and a button. When the user clicks on the button in the child window, I want to retrieve ...

Trouble encountered when using RxJS zip and pipe together

In my Angular Resolver, I am facing a scenario where I need to wait for two server calls. The catch is that the second server call is optional and can be skipped based on user input. This data retrieval process is crucial for loading the next page seamless ...

How can I ensure my variable in Angular 2 waits asynchronously for values to be assigned?

I encountered the following error: TypeError: Cannot read property 'length' of undefined at PaginationComponent.ngOnChanges (pagination.component.ts:38) This is how my PaginationComponent is set up: @Input() items = []; @Input('page-siz ...

Removing chips in Material UI can be easily accomplished by following these steps

Recently, I implemented a feature where chips are generated as the user types in a text field and clicks on create. A chip is then displayed with the entered text. Now, I am looking to add the ability to delete these chips dynamically. You can view the s ...

Iterate over the key-value pairs in a loop

How can I iterate through a key-value pair array? This is how I declare mine: products!: {[key: string] : ProductDTO}[]; Here's my loop: for (let product of this.products) { category.products.push((product as ProductDTO).serialize()); } However, ...

Hide a div element upon selecting an option from a dropdown menu

On iPhone 6plus and lower, I created a dropdown menu that opens when users click on "jobs" or "contact." However, after clicking on these options, the drop-down menu remains open. How can I make it hide automatically after a list item is clicked at this sp ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

Display the contents in a textarea with modal, not as a string

I'm currently working on implementing a modal overlay window with simplemodal that will display the contents of a text area. My goal is to show the rendered output rather than just the string value. For example, if a user enters HTML or includes an im ...

Trigger and intercept events within Angular components

I recently developed an Angular 7 accordion component. You can check out the example on StackBlitz: export class AccordionComponent { @ContentChildren(PanelComponent) panels: QueryList<PanelComponent>; ngAfterContentInit() { this.panels.fo ...

Trouble with Vue bootstrap's <b-modal> function not triggering on @click event

Instead of passing props to the <b-modal> buttons, I want to directly call signinUser() method on @click in my modal when clicking the default OK button. However, the modal doesn't seem to respond to this. The signinUser() method will trigger o ...

Having trouble with building an Ionic3 project, getting the error message: "Execution failed for task ':app:processDebugResources'. > Failed to execute aapt"

My attempt to develop an android app in ionic 3 hit a roadblock when running 'ionic cordova build android' resulted in the error: Execution failed for task ':app:processDebugResources'. > Failed to execute aapt I have integrated plug ...

Implementing the onClick function for the correct functionality in a ReactJS map component

I have designed a mockup and now I am trying to bring it to life by creating a real component. View my component mockup here Starting with something simple, I created 3 buttons and an array. However, when I click on any button, all features are displayed ...

What is the method for starting the JavaScript debugger in Google Chrome?

I'm looking to debug some JavaScript code in Google Chrome. Can anyone guide me on how to do that effectively? ...

What is the process of converting an image taken with the 'react-camera-pro' into a byte array?

I am in the process of capturing an image using a camera through 'react-camera-pro' and I need to figure out how to convert the captured image into a byte array. Here is the snippet of code that I am working with: const camera = useRef(null); ...

CSS Style in Safari does not conceal Div on Tailwind

When switching the screen from desktop to mobile in ReactJS/Tailwind, I have hidden certain images using the following code: <div className="flex shrink flex-row justify-between w-[60%] h-[25%] sm:w-[95%] sm:h-[52%] mb-[-10px] mt-[-15px] lg:mt-0&qu ...

How can I apply an underline effect when hovering over navigation links in a responsive menu?

I've successfully added an underline effect on hover for the navigation menu. However, I encountered an issue with the responsiveness of the menu. When viewed on screens smaller than 600px, the underline effect covers the entire width of the block ins ...

React Typescript Issue: Antd Checkbox value not updating correctly

Hey there, I'm having trouble filling the Checkbox value with my state data as it's not accepting it. Here is the Checkbox Code: <Form.Item label="Active"> <Checkbox value={this.state.selectedRecord.active} /> </Form ...