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

不羁岁月 提交于 2019-12-13 13:02:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!