Call parent component method from child in slot

Viewed 37

Is it possible to call the parent method from a child in a slot? For example:

parent.component.ts

methodFromParentComponent() {
    console.log('fires...')
}

And then something like this:

<parent-component>
    <child-component (click)="methodFromParentComponent"></child-component>
</parent-component>

Ofcourse that won't work. I tried experimenting with ngTemplateOutlet:

<parent-component [slotTemplateRef]="slotTemplateRef">
    <ng-template #slotTemplateRef let-methodFromParent>
        <button  (click)="methodFromParent">Navigate</button>
    </ng-template>
</parent-component>

The problem is, it fires twice, because the event bubbles up, makes sense. Any directions on what I should use?

2 Answers

Your first code sample could work if you add a template reference variable:

<parent-component #parent>
    <child-component (click)="parent.methodFromParentComponent()"></child-component>
</parent-component>

Turns out it works with ngTemplateOutlet. Had to story my methods in an object.

<ng-container *ngTemplateOutlet="layoutTemplate; context: { context: templateContext }">
</ng-container>
<parent-component>
    <ng-template let-context="context">
        <child-component (click)="context.methodFromParentComponent()">
        </child-component>
    </ng-template>
</parent-component>
Related