Ways to invoke the function in a separate component

How can I use ViewChild to call a method in a different component?

I have a method in the piechart component that I want to access from the app component using ViewChild.

In my piechart.component.ts file:

export class PiechartComponent {
  constructor() { }
  pie(){
console.log("Hello World")
}
}

In my app.component.ts file:

export class AppComponent {
 @ViewChild(PiechartComponent) piechart:PiechartComponent;
 constructor(){ }
 pieChart(){ 
 this.piechart.pie();
}
}

In my app.component.html file:

<button (click)="pieChart()">Pie Chart</button>

After clicking the button, I should see the output "Hello world". However, I am encountering the following error: "TypeError: Cannot read property 'pie' of undefined"

Answer №1

Ensure that you insert the child component within the parent component's template

<bar-graph ></bar-graph>
<button (click)="displayGraph()">Display Graph</button>

Live Demo

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

Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application. Everything seems to be working fine, except for the fact that both socket.onmessage and socket.addEventListener('message' are only triggered once. There are no errors in th ...

In Angular 16, allow only the row that corresponds to the clicked EDIT button to remain enabled, while disabling

Exploring Angular and seeking guidance on a specific task. I currently have a table structured like this: https://i.stack.imgur.com/0u5GX.png This code is used to populate the table: <tbody> <tr *ngFor="let cus of customers;" [ngClass ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

Implementing Azure AD authentication with Angular and .NET Core 2 Web API

My goal is to implement authentication in my application using Azure AD Currently, the flow of my application looks like this: User -> AngularApp -> Azure Login -> AngularApp with token -> API Call to backend with token -> Backend verifies ...

What is the best method to completely uninstall Apollo-Angular along with all of its dependencies?

Once I added apollo-angular and @apollo/client to my project, I quickly realized that I no longer needed them. However, simply using "npm uninstall apollo-angular" and "npm uninstall @apollo/client" only removed the main folders but left behind other Apoll ...

Is it advisable to send a response in Express.js or not?

When working with Express.js 4.x, I'm unsure whether to return the response (or next function) or not. So, which is preferred: Option A: app.get('/url', (req, res) => { res.send(200, { message: 'ok' }); }); Or Option B: ...

Encountering issue with ngIf directive in Angular

In my Angular project, I am trying to display data from a variable that is formatted in json. I have successfully done this using *ngfor, but now I also want to add a condition where it checks if msg.who=="Bot". My current code looks like this: <div cl ...

Refining a Collection of Possible Options

If I have an array of type Maybe<int>[] and want to extract only the values that are not None, what is the most efficient approach while ensuring TypeScript recognizes the output as int[]? It seems like declaring the result type as int[] is the way ...

The triggering of Angular Change Detection does not occur when using nested ngFor loops

Currently, I'm deeply engrossed in a substantial Angular project that utilizes NgRx Store. One interesting feature of the app is an infinite scrolling list that displays skeleton items at the end, which are later replaced by real items once the reques ...

Is Drizzle ORM able to handle decimal values in MySQL as strings?

The data structure: export const myTable = mysqlTable( "MyTable", { id: varchar("id", { length: 191 }).notNull(), value: decimal("value", { precision: 7, scale: 4 }).notNull(), createdAt: datetime("created ...

Extract Method Parameter Types in Typescript from a Generic Function

Can we retrieve the type of parameters of methods from a generic interface? For instance, if we have: interface Keys { create: any; ... } type MethodNames<T> = { [P in keyof Keys]: keyof T; } Then, is it feasible to obtain the type of paramete ...

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! ...

Encountering an "Invalid parameter: redirect_uri" error in Keycloak while manually refreshing the page

This is an Angular 17 single-page application utilizing the latest version of keycloak-angular (15.2.1 at the time of writing). I'm facing a perplexing issue where after successfully authenticating and logging out, if I reload the page, it breaks enti ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

Mastering the mapping function in ReactJs for a Map<string, boolean> data structure

Just a quick question, I seem to be stuck on this. Here is my Map: public checkboxOptions: Map<string, boolean>; In the render() function, I want to loop through it like this: renderCheckboxMenu(): any { let menu = <div className={`${style[ ...

Ways to toggle checkboxes to show or hide their child items and subitems

I'm working on creating a straightforward menu that allows users to click on a parent checkbox to expand or collapse its children. The challenge I'm facing is how to make the parent checkboxes expand while hiding the children items within them wh ...

Angular Ahead-of-Time (AOT) compilation causes multiple route definitions to be

Having a bit of trouble configuring ahead-of-time compilation for my lazy-loaded Angular app. The lazy-loaded routes are specified in the app.routes.ts file, which is imported by app.module.ts. Running ngc results in the content of app.routes.ts being mer ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

Need help in NestJS with returning a buffer to a streamable file? I encountered an error stating that a string is not assignable to a buffer parameter. Can anyone provide guidance on resolving this issue?

The issue description: I am having trouble returning a StreamableFile from a buffer. I have attempted to use buffer.from, but it does not seem to work, resulting in the error message below. Concern in French language: Aucune surcharge ne correspond à cet ...

Encountering issues with installing Angular using npm due to errors

When I run npm install, I encounter errors. Though I can get it to work by using npm install --force, I prefer not to rely on the force flag. After reading through the errors, it seems like there might be a version compatibility issue, but I'm having ...