Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular: Why is the variable undefined after ngAfterContentInit?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Output

>Solution :

You’re almost right… One thing: the refs right place is on top the children directly.

<app-parent>
  <app-child #refChild></app-child>
</app-parent>

Then it’s not more undefined:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading