问题
I am successfully using <ng-content></ng-content>
to show a component in a grandchild as answered here: Father-to-son component tree with guest component, but now I would like to use @ContentChild
in that grandchild to access the passed in content, but I can't seem to get anything working.
Here is my attempt using a selector and @ContentChild
in a stackBlitz:
https://stackblitz.com/edit/angular-dpu4pm . No matter what I do, the @ContentChild
is always undefined in TheChild component, but works in TheParent component.
@Component({
selector: 'spinner',
template: `
spinner
`,
})
@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 make this work, or any other approach to access the grandparent from the grandchild would be much appreciated.
来源:https://stackoverflow.com/questions/42775452/how-can-i-use-contentchild-children-in-nested-ng-content