I'm trying to get access to ng content with @ContentChild. To better understand @ContentChild I tried to implement a simple code example. I also did research such as here What's the difference between @ViewChild and @ContentChild?
And many more pages, but I've been sitting on it for hours and have the following problem.
If I want to output the variable this.child
in the console, then undefined
is displayed. Why is that and what am I doing wrong? What do I have to do differently?
app-root:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-parent>
<app-child></app-child>
</app-parent>
`
})
export class AppComponent {}
app-parent
import { AfterContentInit, Component, ContentChild} from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-parent',
template: `
<ng-content></ng-content>
`
})
export class ParentComponent implements AfterContentInit {
@ContentChild('refChild') child: any;
ngAfterContentInit() {
console.log('ngAfterContentInit');
console.log(this.child);
}
}
app-child
import { Component} from '@angular/core';
@Component({
selector: 'app-child',
template: `
<div #refChild>
<h1>Child headline</h1>
<h2>Child subheadline</h2>
</div>
`
})
export class ChildComponent {}