Angular Accessing ng template inner component
Let's say we have a component called TopComponent
with this pattern:
<ng-template #top>
<inner-selector #inner></inner-selector>
</ng-template>
The code is 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 access the #inner component from here
}
}
I can access the component #top
using this code:
@ViewChild('top') topComponent: TopComponent;
How can I access a component #inner
from the same class?
I tried to use @ContentChild('inner')
but still get undefined
.
PS. I know I can create another component, use it instead, <ng-template>
and access all the children I need. But can this be somehow avoided?
source to share
Use Descendants @ViewChild ('inner', {Descendants: true}) inner: InnerSelector;
here's the fill code: 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);
}
}
source to share