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:
<p-contextMenu [appendTo]="contextMenuHolder" [model]="items"></p-contextMenu>
Obviously it fails as the contextMenuHolder
does not exist in the child, but in its parent:
Angular: Identifier 'contextMenuHolder' is not defined. The component declaration, template variable declarations, and element references do not contain such a member
Can you reference a parent's template variable from a child component?
Edit:
Plunkr with it broken. This plunkr shows it not working, but no error messages.
The documentation for
appendTo
saysMaybe a service can resolve the issue :
In your
app.ts
, you inject the service and set the value. In yourcomponent.ts
, you inject the service and get the value.I did not tested it but it should work. If the
contextMenu
can change, you will have to use event listeners or observable.Thanks to Ludovic Guillaume I was able to find a solution:
https://plnkr.co/edit/kwnkSKDPFs1Bp2xOHqIu
child.ts:
Here, the child component has built the context menu with the items it wants in the menu. This menu needs to reside in the parent (sometimes this is necessary for styling or positioning reasons). The child has a
parentContext
object that will be set during it'sonInit
phase of the lifecycle.parent (app.ts):
The parent sets the object in the service during it's
onInit
stage. Initially I thought this had to be during theafterViewInit
, but this ended up being too late in the lifecycle.service: