angular2 call function of parent component

Viewed 119427

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?

5 Answers

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 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()
}

In parent html:

<child [parent]="this"></child>

In child component:

@Input() parent: ParentComponent;
// then do whatever with `this.parent`

Events have their places, but I don't see anything else is simpler than this.

Related