Father to Son component tree with guest component

In Angular 2, I have a component hierarchy. However, in the tree I need to show another element that is separate from the hierarchy of objects. It is a spinner component. Somehow he does not want to appear.

<parent> <child> <grandchild> <spinner></spinner> </grandchild> <child> </parent> 
  • parent contains child in the template,
  • child contains grandchild in the template.
  • grandchild does not contain a spinner in the template, but wants to show it (for this, it uses ng-content ). Or perhaps at some point the child will want to show the spinner instead.

How do I make it work? Should a parent always indicate potential children? PLease let me know what I'm doing wrong.

Plunker example

+2
source share
1 answer

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

This way you can pass the child components to the 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 as

 <child><my-spinner></my-spinnger></child> 
+2
source

Source: https://habr.com/ru/post/1265413/


All Articles