问题描述
我正在使用primefaces primeng组件p-contextmenu
开发一个angular 4应用程序.我试图告诉子元素使用父组件的模板变量.
I am working on an angular 4 application using a primefaces primeng component, p-contextmenu
. I am trying to tell a child element to use a template variable of a parent component.
app.html:
<div>
<router-outlet></router-outlet>
<div #contextMenuHolder></div>
</div>
mycomponent.html:
mycomponent.html:
<p-contextMenu [appendTo]="contextMenuHolder" [model]="items"></p-contextMenu>
显然,它失败了,因为contextMenuHolder
在子级中不存在,但在其父级中不存在:
Obviously it fails as the contextMenuHolder
does not exist in the child, but in its parent:
您可以从子组件中引用父模板的变量吗?
Can you reference a parent's template variable from a child component?
损坏了的朋克.此插件显示它无法正常工作,但没有错误消息.
Plunkr with it broken. This plunkr shows it not working, but no error messages.
推荐答案
appendTo
的文档说
也许服务可以解决问题:
Maybe a service can resolve the issue :
@Injectable()
export class ContextMenuHolder {
contextMenu: any; // TODO set a type (HTMLElement?)
getContextMenu() {
return this.contextMenu;
}
setContextMenu(contextMenu: any) {
this.contextMenu = contextMenu;
}
}
在您的app.ts
中,注入服务并设置值.在您的component.ts
中,您注入了服务并获得了价值.
In your app.ts
, you inject the service and set the value.In your component.ts
, you inject the service and get the value.
我没有测试它,但是它应该工作.如果contextMenu
可以更改,则必须使用事件侦听器或可观察的事件.
I did not tested it but it should work. If the contextMenu
can change, you will have to use event listeners or observable.
这篇关于角度-子组件可以引用父模板的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!