Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 call function of parent component

Tags:

angular

I have an app where I have an upload component where I can upload a file. It is embedded in the body.component.

On upload, it should use a function (e.g. BodyComponent.thefunction()) of the parent component (do a call to update the data): but only if it the parent is specifically the body.component. The upload might also be used elsewhere with different behavior.

Something like parent(this).thefunction(), how to do that?

like image 238
PascalVKooten Avatar asked Mar 11 '16 13:03

PascalVKooten


People also ask

How can we call parent component method in child component?

A ViewChild is a decorator which is used when we want to access a child component inside the parent component, we use the decorator @ViewChild() in Angular. Here I have declared a variable name child as decorator @ViewChild(). As shown below we can access childMethod of child component inside the parent component.

How do you call the parent component method from a child component in Angular 11?

To call a parent component method from a child component, you need to use an Angular EventEmitter. Emitting events allows your components to communicate with one another when a certain action has been executed, in this example the action is on click.


2 Answers

I would create a custom event in the child component. Something like this:

@Component({   selector: 'child-comp',   (...) }) export class ChildComponent {   @Output()   uploaded = new EventEmitter<string>();    uploadComplete() {     this.uploaded.emit('complete');   } 

Your parent component could register on this event

@Component({   template `     <child-comp (uploaded)="someMethod($event)"></child-comp>   `,   directives: [ ChildComponent ] }) export class ParentComponent {   (...)    someMethod(event) {   } } 

Another way would be to inject the parent component in the child one, but they will be strongly linked together...

like image 162
Thierry Templier Avatar answered Sep 17 '22 20:09

Thierry Templier


Below is the code that worked for me in the latest

Angular 5+

class ChildComponent {   @Output() myEvent = new EventEmitter<string>();    callParent() {     this.myEvent.emit('eventDesc');   } } 

In ParentTemplate's template

<child-component (myEvent)="anyParentMethod($event)" 
like image 34
Shabbir Dhangot Avatar answered Sep 19 '22 20:09

Shabbir Dhangot