How to Trigger Child Component Functions from Parent Methods in Angular 8

I am struggling to call a child component method from my parent component and pass an object. When I try to do so, I encounter the following error: Cannot read property 'RunMe' of undefined

What am I missing?

Child component:

runMe = (item)  => {
    this.cdr.detectChanges();
    if (item.hidden) {
        this.showErrorMsgEvent.emit();
    } else {
        this.highLightEvent.emit(item);
    }
}

Parent component:

@ViewChild(childComponent, { static: true }) childComponent;

ListenIframeEvents(){
    window.addEventListener("message", this.displayMessage, false)
  }
  displayMessage (item) {
    this.childComponent.RunMe(item)
  }


<child-component #childComponent></child-component>

After researching online, I found suggestions to add the # selector but it did not work for me.

Just to clarify, when I run this.childComponent.RunMe() function under the ngOnInit(), it works perfectly fine. I am puzzled as to what I am doing wrong.

Answer №1

The issue lies in this particular line of code:

window.addEventListener("message", this.displayMessage, false)

To fix it, update the code to:

window.addEventListener("message", this.displayMessage.bind(this), false)

UPDATE:

When passing a method as a parameter to a function, it loses its original context (this). To maintain the context, we can use .bind() to explicitly set it.

For more information, visit

Answer №2

There appear to be two potential issues at play in this scenario.
Firstly, it's possible that the child component is positioned under certain structural directives like *ngIf. In this case, setting the child as {static: false} may resolve the issue.
Alternatively, the problem could stem from using the "displayMessage" method too early, before the parent template has been fully rendered. If this is the case, consider moving the this.displayMessage(...) call inside the ngAfterViewInit Angular lifecycle hook.

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

Heroku encounters issue with Node.js and Angular build process

I have encountered an issue with my app deployment. Everything works fine locally, but when I try to deploy, the build fails and generates the following output log: -----> Node.js app detected -----> Creating runtime environment NPM_CONFIG_ ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Models in Typescript that are interrelated with Loopback

I'm currently working on defining connected models including the HasMany relationship in the context of @types/loopback definitions My approach involves creating an interface for HasMany and its implementation: interface IHasMany { /** ...

How to remove the border of the MUI Select Component in React JS after it has been clicked on

I am struggling to find the proper CSS code to remove the blue border from Select in MUI after clicking on it. Even though I managed to remove the default border, the blue one still persists as shown in this sandbox example (https://codesandbox.io/s/autumn ...

Experience the convenience of selecting multiple rows with checkboxes, while enjoying the simplicity of selecting a single row by clicking

Hey there! I'm looking to enable multiple selection using checkboxes and single selection by clicking on a row. Does anyone know how I can achieve this within the same table? Check out this link for some ideas ...

What is the best way to determine if several simultaneous tasks have been completed?

Implementing multiple parallel actions in an Angular component has proven to be challenging for me. Following each action (foo), I subscribe to its result. I've been attempting to determine if any actions are currently running or have completed using ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Encountering a problem when making a HTTPS GET request to a REST API using

I am currently running an Angular application that utilizes an external API to fetch country ISOs. However, I am encountering an error with the API since it uses HTTPS. Interestingly, when I implement a proxy in my Angular local environment by mapping /is ...

What is the process for retrieving the chosen country code using material-ui-phone-number?

When incorporating user input for phone numbers, I have opted to utilize a package titled material-ui-phone-number. However, the challenge arises when attempting to retrieve the country code to verify if the user has included a 0 after the code. This infor ...

Strange behavior observed when redirecting in an Angular component inside an async function block

My app is receiving FCM messaging notifications successfully, but I'm facing an issue when trying to trigger a router navigation. Specifically, I want to display a page that mimics the standard Android incoming call screen when a call notification is ...

What is the process for developing a personalized set of tslint rules?

I am looking to create a comprehensive TypeScript coding guideline that can be easily shared across various projects. Instead of repeatedly copying and pasting a tslint.json file, I aim to have a unified version to avoid any divergence issues. My guidelin ...

Unable to load component "/" in Angular 2 Rc.1 router

I've been trying to implement the new router from the rc.0 update (actually using rc.1), but I'm running into an issue with the outlet not loading the "Welcome" component. Below is the code in app.component.ts import { Component } from '@a ...

Utilizing an object as a prop within React-router's Link functionality

Looking for a solution to pass the entire product object from ProductList component to Product component. Currently, I am passing the id as a route param and fetching the product object again in the Product component. However, I want to directly send the ...

When Typescript calls the toString method on a Function, it produces unexpected characters like "path_1, (0, promises.writeFile)"

I'm currently attempting to convert a function into a string for transmission to a worker thread for execution. However, when imported code is included, the resulting string contains strange characters. import { HttpStatus } from '@nestjs/common& ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...

ng2 - Comparing DevExtreme and Telerik Kendo UI

Our team is embarking on a new software project utilizing Angular2, typescript, and HTML5. We are considering two options for UI components: - DevExtreme - Telerik Kendo UI Which of these would be the best choice in your opinion? Thank you! ...

What is the best way to organize my NPM package with separate directories for types and functions?

I am currently working on developing a custom NPM package that will serve as a repository for sharing types and functions across my project. Let's name this project wordle. Given the emphasis on types, it is worth noting that I am using TypeScript for ...

Encountered an issue when trying to convert JSON into an array and loop through it in an HTML file using a

Currently, I am working on a project involving Angular where I am retrieving data from an API through a GET call. Specifically, one column's data is being converted from JSON to an array. However, when attempting to iterate over this array in the HTML ...

What is the best way to accomplish this using typescript/adonis?

While exploring some code examples on Bitbucket, I came across a sample that demonstrated how to paginate query results using JavaScript. However, as I attempted to apply it in my project, I encountered difficulties in declaring the types required for the ...