3

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

Output

coder
  • 129
  • 7

1 Answers1

1

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

For the other direction you can use Services, EventEmitter or the Host decorator like this (it's the child constructor):

constructor(@Host() parent: ParentComponent) {
 console.log("Here it is", parent)
}
Flo
  • 2,232
  • 2
  • 11
  • 18
  • I'm trying to do it the other way around. From Parent Component to Child Component. Getting the same error undefined in the console. Although I think it should be correct. https://stackblitz.com/edit/angular-ivy-qxmk1e?file=src/app/app.component.ts – coder Dec 28 '22 at 16:29
  • 1
    That's not possible. Like the name `viewChild` say it works only in this direction. From child to parent use EventEmitter, Services or the @Host() decorator. Look at my updated answer. – Flo Dec 28 '22 at 16:41