Digamos que tenemos un componente llamado TopComponent con una plantilla como esta:
<ng-template #top> <inner-selector #inner></inner-selector> </ng-template>Su código es simple:
//... imports ... @Component({ // selector, styles etc }) export class TopComponent implements AfterViewInit { @ViewChild('top') topComp : NgbModal; // NgbModal is a type provided by some 3rd-party library // I can't modify it ngAfterViewInit() { // let's access the #inner component from here } } Puedo acceder al componente #top usando este código:
@ViewChild('top') topComponent: TopComponent; ¿Cómo puedo acceder al componente #inner desde la misma clase?
Intenté usar @ContentChild('inner') pero sigo undefined .
PD. Sé que puedo crear otro componente, usarlo en lugar de <ng-template> y acceder a todos los elementos secundarios necesarios desde él. Pero, ¿se puede evitar esto de alguna manera?
Usar descendientes @ViewChild('inner', {descendants: true}) inner: InnerSelector;
aquí está el código de relleno: https://plnkr.co/edit/MtVhHuAtPXZzC7GLOidF?p=preview
@Component({ selector: 'inner-selector', template:'inner-selector here' }) export class InnerSelector { myVar = 0; } @Component({ selector: 'my-app', template: ` <div> <ng-template #top> <inner-selector #inner></inner-selector> </ng-template> <ng-container [ngTemplateOutlet]="top"></ng-container> </div> `, }) export class App { @ViewChild('inner', {descendants: true}) inner: InnerSelector; constructor() { this.name = `Angular! v${VERSION.full}` } ngAfterViewInit() { console.log(this.inner); } }