2

In Angular 2 I have a hierarchy of components. Within the tree, however, I need to show yet another element which is decoupled from the object hierarchy. It will be a spinner component. Somehow it does not want to show up.

<parent>
    <child>
        <grandchild>
            <spinner></spinner>
        </grandchild>
    <child>
</parent>
  • parent includes child in the template,
  • child includes grandchild in the template.
  • grandchild does not include spinner in the template, but wants to show it (it uses ng-content for that). Or perhaps, at some point the child would want to show the spinner instead.

How do I get it to work? Does a parent always have to specify possible children? PLease let me know what I'm doing wrong.

The example plunker

user776686
  • 7,933
  • 14
  • 71
  • 124

1 Answers1

2

If you add <ng-content></ng-content> to the template of a component, then child elements are displayed instead of <ng-content></ng-content>.

This way you can pass child components to parents.

@Component({
  selector: 'child'
  template: `<grand-child><ng-content></ng-content></grand-child>`
})
@Component({
  selector: 'grand-child'
  template: `some content before <ng-content></ng-content>some content after`
})

Then you can use it like

<child><my-spinner></my-spinnger></child>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks, but this is exactly how I thought it would work - in the plunker you'll see `ng-content` in the Grandchild template. (I edited my post to be more precise.) Or is there any nuance I am overlooking? – user776686 Oct 14 '16 at 14:12
  • Sorry, didn't see the Plunker. https://plnkr.co/edit/J1qHqdjRn7NYgTyqIxLv?p=preview. Your Plunker didn't contain any ``. Perhaps not pressed save? – Günter Zöchbauer Oct 14 '16 at 14:19
  • Sorry, my fault, indeed the plunker had not been saved and did not contain granchild. Now it should be up-to-date – user776686 Oct 14 '16 at 14:27
  • The whole chain needs `` (the spinner doesn't if it doesn't get children passed) https://plnkr.co/edit/GpwMh0BLbq3GhJxVXDiE?p=preview – Günter Zöchbauer Oct 14 '16 at 14:30
  • Yes, indeed, yet without and element then. Perfect, thanks. – user776686 Oct 14 '16 at 14:38
  • @GünterZöchbauer - How would I use ContentChild here? I have posted a separate question here: http://stackoverflow.com/questions/42775452/how-can-i-use-contentchild-children-in-grandchild – Learning2Code Mar 13 '17 at 23:48