Invoke a component's function in a different component

Upon clicking the button, I am trying to execute the 'exportHistoryToCSV' method within this component, which in turn calls a method from another component. However, I am encountering an error.

    @UntilDestroy()
@Component({
  selector: 'device-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DeviceFormComponent implements OnInit, EditorComponent {
  @ViewChild('deviceHistoryComponent')
  deviceHistory!: DeviceHistoryComponent;

  constructor() {}

  ngOnInit() {
  }

  exportHistoryToCSV() {
    this.deviceHistory.exportToCSV();
  }
}

Method 'exportToCSV' in the other component

      exportToCSV() {
    this.historyStore.exportHistoryToCsvFile();
  }

Error:

  core.mjs:7640 ERROR TypeError: Cannot read properties of undefined (reading 'exportToCSV')
    at DeviceFormComponent.exportHistoryToCSV (device-form.component.ts:59:24)
    at DeviceFormComponent_div_1_button_5_Template_button_click_0_listener (template.html:10:63)
    at executeListenerWithErrorHandling (core.mjs:15778:16)
    at wrapListenerIn_markDirtyAndPreventDefault (core.mjs:15813:22)
    at HTMLButtonElement.<anonymous> (platform-browser.mjs:459:38)
    at _ZoneDelegate.invokeTask (zone.js:406:31)
    at Object.onInvokeTask (core.mjs:26365:33)
    at _ZoneDelegate.invokeTask (zone.js:405:60)
    at Zone.runTask (zone.js:178:47)
    at ZoneTask.invokeTask [as invoke] (zone.js:487:34)
handleError @ core.mjs:7640
handleError @ core.mjs:13387
executeListenerWithErrorHandling @ core.mjs:15781
wrapListenerIn_markDirtyAndPreventDefault @ core.mjs:15813
(anonimowa) @ platform-browser.mjs:459
invokeTask @ zone.js:406
onInvokeTask @ core.mjs:26365
invokeTask @ zone.js:405
runTask @ zone.js:178
invokeTask @ zone.js:487
invokeTask @ zone.js:1661
globalCallback @ zone.js:1692
globalZoneAwareCallback @ zone.js:1725

Answer №1

Ensure that your DeviceFormComponent is within the same DOM as your other component to avoid receiving an error message saying it is undefined. Refer to the example below:

<h1>Parent Component</h1>
<button (click)="onClick()">Call Another Component</button>
<app-another-component></app-another-component>
@Component({...})
export class ParentComponent {
 @ViewChild(AnotherComponent) anotherOne!: AnotherComponent;

 onClick(): void {
   this.anotherOne.sayHello();
 } 
}

AnotherComponent

@Component({...})
export class AnotherComponent {
  sayHello(): void {
    console.log('Greetings from Another Component');
  }
}

If you want to learn more about how ViewChild works, check out the official documentation

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

Issue with retrieving properties in Angular template due to undefined values in HTML

As a newbie to Angular, I am dedicated to improving my skills in the framework. In my project, I am utilizing three essential files: a service (Studentservice.ts) that emits an observable through the ShowBeerDetails method, and then I subscribe to this ob ...

Angular 2 Routing 3.0: Paying Attention to Letter Case

let routesList: Routes = [ { path: 'x', component: xComponent }, { path: 'y', component: yComponent }, { path: 'zComponent', component: zComponent } ]; When entering "x" in the URL, it navigates to the component page. Ho ...

Retrieve the value of a variable to access an object property dynamically in React Native using TypeScript

As I attempted to create dynamic styles for this component, my goal was to determine the styles based on a string passed in as a property. Here is the code snippet: export type MyComponentProps = { styleName: string; } const MyComponent = (props: MyComp ...

Using a Type Guard in Typescript to check if an environment variable matches a key in a JSON object

I am currently working on creating a Type Guard to prevent TypeScript from throwing an error on the final line, where I attempt to retrieve data based on a specific key. TypeScript is still identifying the environment variable as a string rather than a rec ...

Tips for embedding an Angular application within another Angular application

I am working on two Angular projects at the moment. The first one is named App1, while the second one is called Angular Form Editor. My goal is to integrate the Form Editor into the App1 project. What steps should I take in order to achieve this integrat ...

Guide to selecting a specific element in a loaded template depending on an *ngIf statement

I'm having trouble accessing an element in my template using a template variable as it keeps returning as undefined. At a specific route in my application, my component makes a call to fetch some data within the forkJoin method from rxjs. Due to the ...

Testing the use of rxjs fromEvent in Angular while mocking subscriptions

In the Angular component, I have an array of objects representing companies that are provided via @Input(). Upon loading this data, which is obtained from an HTTP request, I assign it to another variable called filteredList, which is used in an *ngFor dire ...

I have to create a duplicate for the clipboard containing a dynamic variable in Angular

CSS Note: The Technical.url variable in the specification is constantly changing, and every time I click the button, I want to copy the URL. <div fxLayout="column" fxLayoutAlign="center start" fxFlex="70" class="" ...

Is there a way to safeguard against accidental modifications to MatTab without prior authorization?

I need to delay the changing of the MatTab until a confirmation is provided. I am using MatDialog for this confirmation. The problem is that the tab switches before the user clicks "Yes" on the confirmation dialog. For instance, when I try to switch from ...

Navigating through template files in Angular 2 components

Currently, I am working on developing a top-level component that requires an input of type @Input(): Object. This object needs to contain an array of components, which will be iterated through using *ngFor, and the templates of these components must be p ...

Display excerpts of code within an Angular application within the HTML segment

I'm currently developing a tutorial page using Angular where I intend to display code snippets in various programming languages such as 'Java', 'TypeScript', 'C#', and 'Html'. Although there is a snippet called ...

Creating a new Angular2 component for a separate URL path

In my scenario, I have a PageComponent that gets refreshed with new data when the URL changes (using PageService). It currently utilizes the same PageComponent object, but I am looking to make it a new object when the URL changes. 1st Question: How can ...

How to optimize CSS loading in Angular 15

I am developing an Angular application with Server-Side Rendering (SSR). How can I preload/prefetch the entire styles.css file by adding <link rel="preload" href="/styles.css" as="style" /> to the head section or Link h ...

Unable to link to 'amount' because it is not a recognized attribute of 'ng-wrapper'

I recently made some changes to my code and now I'm encountering the error message "Can't bind to 'count' since it isn't a known property of 'ng-container'" Instead of having both the notification component and notificat ...

Tips for customizing the background color in the angular2-tree component

As a newcomer to Angular 4, I have been attempting to incorporate angular2-tree into my project. However, I am struggling to figure out how to dynamically set the background color of each node. I have been trying to include a "color" attribute in our dat ...

Transferring form state information between parent and child elements

In my development project using Angular 2, I encountered an issue with managing a long and complex form by splitting it into a parent component and two child components for better organization. The challenge arose when I needed to track the form status for ...

Utilizing Session storage throughout an Angular 2 application

I currently store a session variable as a JSON value in my home.component.ts. This variable needs to be accessed in various locations within the application. This is my code snippet: .do(data => sessionStorage.setItem('homes', JSON.stringif ...

Unable to download tsc through the Terminal on OS X

Struggling to install tsc, encountering numerous errors upon running it. Reinstalled node and npm multiple times, adjusted npm flag to verbose, here's the output: Mitch:~ mitch$ npm install -g typescript npm info it worked if it ends with ok ... Fe ...

Showing an error message upon submission in Angular 4 according to the server's response

Struggling for hours to display an error message when a form submits and returns an error status code. The solution seems elusive... In the login form component below, I've indicated where I would like to indicate whether the form is valid or invalid ...

Determine the type and create an instance of a fresh class

In my app, I have a function that handles all API requests. Any interaction I make goes through this function. I'm trying to set a specific return type for this function, but the return type is of a class. In order to use the methods of this class, I ...