How can I use ContentChild / Children in a nested <ng-content>

I successfully use <ng-content></ng-content> to show the component in the grandson, as it says here: The component tree from father to son with the guest component , but now I would like to use @ContentChild in this grandson, but I don’t I can make nothing work.

Here is my attempt to use the selector and @ContentChild in the forked plunk from the question mentioned: https://plnkr.co/edit/ohCz9JWTrvogzomCO7oe?p=preview . No matter what I do, @ContentChild always undefined.

 @Component({ selector: 'my-app', template: ` works <the-parent><spinner #spin></spinner></the-parent> `, }) @Component({ selector: 'the-parent', template: 'this is parent <the-child><ng-content #content></ng-content></the-child>' }) export class TheParent implements AfterViewInit{ @ContentChild('spin') spin; ngAfterViewInit() { alert('parents spin is '+typeof this.spin); //object } } @Component({ selector: 'the-child', template: 'this is child <ng-content></ng-content>' }) export class TheChild implements AfterViewInit{ @ContentChild('spin') spin; @ContentChild('content') content; ngAfterViewInit() { alert('childs spin is '+typeof this.spin); //undefined alert('childs content is '+typeof this.content); //undefined } } 

Any advice on how to do this job or any other approach to accessing grandparents from a grandson would be greatly appreciated.

+5
source share

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


All Articles