[英]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
:我尝试使用
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
.原来它适用于
ngTemplateOutlet
。 Had to story my methods in an object.不得不在 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.