简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM