Problem with Invoking method of parent component from child component in Angular 4

Despite having all my event emitters set up correctly, there's one that seems to be causing issues.

child.ts:

@Component({
    ... 
    outputs: ['fileUploaded']
    })

export class childComponent implements OnInit {
  ...
  fileUploaded = new EventEmitter<boolean>();
  ...
  randomMethod(){
     ...
     this.fileUploaded.emit(true);
  }

}

The randomMethod() function is triggered from the parent component as illustrated in parent.ts, but not from child.html.

parent.html


...
<child (fileUploaded)="onSubmit($event)"></child>
..

parent.ts

export class parentComponent {
   ...
   theChild = new childComponent;
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }

  functionCallsChild(){
     this.theChild.randomMethod();
     ...
     this.theChild = new childComponent;
  }
}

Even though I expect "in onSubmit()" to be logged by my app, it never shows up. Why might onSubmit() not be getting called? I also attempted removing the instantiation of a new child object on the last line, but it didn't solve the problem.

Answer №1

Perhaps the reason for choosing this particular method is not entirely clear to me, or what exactly you need it for. From what I understand, the recommended approach is to utilize the EventEmitter from the child component to communicate with its parent component. This implies that the event triggering the .emit() function should be located within the child.html file. Try implementing it as follows:

child.html

<div (click-or-whatever-fires-what-you-want)="randomMethod()"></div>

child.ts:

@Component({
    ... 
    })

export class childComponent implements OnInit {
  ...
  @Output() fileUploaded = new EventEmitter<boolean>();
  ...
  randomMethod(){
     ...
     this.fileUploaded.emit(true);
  }

}

parent.html

...
<child (fileUploaded)="onSubmit($event)"></child>
..

parent.ts

export class parentComponent {
   ...
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }
}

I hope this explanation proves useful.

Answer №2

To communicate between a parent component and a child component, you can make use of the @Output emitter which triggers on any event in the child component. I implemented this technique in the commenting section to update the count in the parent component by invoking a method in the child component.

Parent.ts

/** Update the count from the child component */
UpdateCount(id) {
this.getTotalCommentCountByGroupId(id);
}

Parent.HTML

<srv-group-feed [LiveFeedInput]="groupPostRes" 
(CommentCount)="UpdateCount($event)"></srv-group-feed>

Child.ts

this.CommentCount.emit(data you want to pass);

In the child.ts file, declare the @Output event globally like this:

@Output() CommentCount = new EventEmitter<string>();

Answer №3

Consider attempting it in this manner:

@Output()
  fileUploaded = new EventEmitter<boolean>();

Let go of:

outputs: ['fileUploaded']

Explore the documentation here! :)

Answer №4

Avoid using the new operator to create child components.

Instead, utilize @ViewChild() to access and reference the child component.

Answer №5

It seems like you may need to adjust your approach when selecting the child component. Consider using ViewChild in the following manner:

parent.html:

<child #theKid (fileProcessed)="onSubmit($event)"></child>

parent.ts:

export class MainParentComponent {
   ...
   @ViewChild('theKid') theKid;
   isSubmitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('Executing onSubmit() method');
     this.isSubmitted = event;
  }

  makeCallsToChild(){
     this.theKid.customMethod();
     ...
  }
}

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

Annoying border problem encountered with Angular material column header

After upgrading Angular Material to version 9, I encountered an issue where a bottom border appears under the sorted column heading in my mat-table. Strangely, the border disappears when clicked upon. Upon inspecting the browser's CSS, I discovered t ...

Retrieving an array of objects from an API and attempting to store it using useState, but only receiving an empty

I have been working on fetching data from an API, storing it in Redux store initially, and then attempting to retrieve it using useSlector to finally save it in local state. Despite getting the data when I console.log it, I am unable to successfully store ...

Having trouble obtaining the ref.current.offsetWidth?

I have been working on creating a contextMenu. My goal is to retrieve the offsetWidth and offsetHeight from ref.current, but when I console.log it, it shows as undefined. const ContextMenu: React.FC<ContextMenuProps> = props => { const thisCom ...

Dealing with permission-based errors on the interface

I've been working on implementing authorization in my Angular project for hours now, following this example. I have created an HTTP interceptor to handle errors, but I'm unsure how to display these errors in my login view. I have tried passing a ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

What is the best way to mock an internal function within my route using sinon?

Currently, I have my own internal function defined in the greatRoute.ts file: //in greatRoute.ts async function _secretString(param: string): Promise<string> { ... } router .route('/foo/bar/:secret') .get( async (...) => { ...

Unable to find a solution to Angular response options

I'm having trouble saving an item to local storage when receiving a 200 response from the backend. It seems like the request status is not being recognized properly. options = { headers: new HttpHeaders({ 'Content-Type': &apos ...

Angular error: Trying to access the sort property of an undefined value

I am currently working on creating a sorting function and pipe for a table. I found guidance on how to do this by following a tutorial at this link, and here is the plunker example. In the example, the table header should be clickable to trigger the sort() ...

The module named "mongoose" does not have any member called 'PaginateResult' exported

I'm facing an issue while trying to add the necessary types for "mongoose-paginate" in my Angular 4 project setup with "angular-cli". The problem arises when Webpack throws an error. import {PaginateResult} from "mongoose"; ... getAll(page: number) ...

The NGRX state in Angular is not being properly saved by the local storage

Currently, I am utilizing NGRX for state management within my Angular application. While NGRX is functioning correctly, I have encountered an issue with using local storage to persist the NGRX state. Upon refreshing the browser, the NGRX data reverts back ...

What is the best way to update the mat-tab when the routeParameters are modified?

I need to reinitialize the mat-tab-group in order to make the first tab active when there is a change in the routeParams. ts file: public index = 0; ngOnInit() { this.subscription = this.route.params.subscribe((routeParams: Params) => { // some ...

What is the best way to integrate Tawk.to into a React application while using typescript?

Having some issues integrating tawk.to into my website built with React and TypeScript. I have installed their official npm package, but encountered an error message: import TawkMessengerReact from '@tawk.to/tawk-messenger-react'; Could not fin ...

What is the correct way to input the 'name' HTML attribute in an Ant Design select element?

I am facing an issue with the 'name' attribute in my Ant Design Select component. When trying to set the 'name' attribute, I encountered an error message that is causing issues. https://i.stack.imgur.com/Lzb4t.png Ant Design Select Co ...

Display the notification list by utilizing the "ToastController" function

Upon entering the home screen, I want to notify the user by displaying a list of messages from a firebase collection. The field to be displayed is "text", but I only want to show messages with the "read" field set as false. Once a message is shown, its "re ...

How can the file system module (fs) be utilized in Angular 7?

Hello, I am currently working with Angular 7. I recently attempted to utilize the fs module in Typescript to open a directory. However, I encountered an error message stating: "Module not found: Error: Can't resolve fs". Despite having types@node and ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...

Is it necessary to import the same .less file into every Angular component template?

Within my angular cli project, the setup includes: angular-cli.json: "styles": [ "styles/styles.less" ], styles.less: @import 'general'; general.less: .pointer { cursor: pointer; } In the component's styles .less file, ...

What is the best way to retrieve the previous URL in Angular after the current URL has been refreshed or changed

Imagine being on the current URL of http://localhost:4200/#/transactions/overview/5?tab=2 and then navigating to http://localhost:4200/#/deals/detail/ If I refresh the deals/detail page, I want to return to the previous URL which could be something like h ...

Having trouble installing the Angular/CLI on macOS Mojave due to a node-pre-gyp error?

I recently formatted my iMac and deleted all files on the hard drive. However, upon installing Angular CLI 7, I encountered an error log message in the terminal console. Environment macOS: Mojave 10.14.2 node: v10.15 npm: 6.4.1 Console Error miguels- ...