Как я могу использовать ContentChild/Children во вложенном <ng-content>

Я успешно использую <ng-content></ng-content> чтобы показать компонент внука, как здесь ответили: Дерево компонентов от отца к сыну с гостевым компонентом, но теперь я хотел бы использовать @ContentChild в этом внуке, но я не могу заставить что-либо работать.

Вот моя попытка с помощью селектора и @ContentChild в стеке Blitz: https://stackblitz.com/edit/angular-dpu4pm. Что бы я ни делал, @ContentChild всегда неопределен в компоненте TheChild, но работает в компоненте TheParent.

@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
  }

}

Буду очень признателен за любой совет о том, как сделать эту работу, или любой другой подход, чтобы получить доступ к бабушке и дедушке от внука.

0 ответов

Другие вопросы по тегам