angular2 call function of parent component

Angular

Angular Problem Overview


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?

Angular Solutions


Solution 1 - Angular

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

Solution 2 - Angular

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)"

Solution 3 - Angular

Solution without events involved.

Suppose that I have a ChildComponent and from that I want to call the method myMethod() which belongs to ParentComponent (keeping the original parent's context).

Parent Component class:
@Component({ ... })
export class ParentComponent {

    get myMethodFunc() {
        return this.myMethod.bind(this);
    }

    myMethod() {
         ...
    }
}
Parent template:
<app-child [myMethod]="myMethodFunc"></app-child>
Child template
@Component({ ... })
export class ChildComponent {

    @Input() myMethod: Function;
    
    // here I can use this.myMethod() and it will call ParentComponent's myMethod()
}

Solution 4 - Angular

You can inject the parent component to the child component.

For more details see

Otherwise using @Output() is preferred to communicate from child to parent.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPascalVKootenView Question on Stackoverflow
Solution 1 - AngularThierry TemplierView Answer on Stackoverflow
Solution 2 - AngularShabbir DhangotView Answer on Stackoverflow
Solution 3 - AngularFrancesco BorziView Answer on Stackoverflow
Solution 4 - AngularGünter ZöchbauerView Answer on Stackoverflow