angularng-templateng-content

Call parent component method from child in slot


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?


Solution

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