Home > Enterprise >  Why am I getting Content child as undefined?
Why am I getting Content child as undefined?

Time:03-05

Here is the child component html

<div #hooksContainer style="display: grid;overflow: auto;max-height: 35vh;border: 1px solid black;border-radius: 5px;padding: 10px;">
  <!-- Input Var {{inputVar.data}} -->
  <ng-content>
    <!-- this is space for any content passed from outside -->
  </ng-content>
  <ng-content select="header">
    <!-- this is space for any content passed from outside with tag header-->
  </ng-content>
</div>

and this is the component file for child

import { AfterContentChecked, AfterContentInit, ChangeDetectorRef, Component, ContentChild, ElementRef, Input } from '@angular/core';

@Component({
  selector: 'app-hook-cycles',
  templateUrl: './hook-cycles.component.html',
  styleUrls: ['./hook-cycles.component.scss']
})
export class HookCyclesComponent implements   AfterContentInit, AfterContentChecked{
  @ContentChild("header")
  public headerContent!: ElementRef;

  @Input()
  public inputVar!: { data: string, otherData: { isTrue: boolean, check: string } };
  constructor(private cdref: ChangeDetectorRef) {
  
  }
  ngAfterContentChecked(): void {
    console.log("Content Child headerContent: ", this.headerContent);
  }
  ngAfterContentInit(): void {
    console.log("Content Child headerContent: ", this.headerContent);
  }
}

and this is the app component html file

<div style="padding-top: 25px;">
  <h1 style="text-align: center;">App Works!!</h1>
  </div>
<app-hook-cycles>something sent from outside<header>[Header] this was too</header></app-hook-cycles>

and this is the result of console.log [consoleLog]: https://i.stack.imgur.com/4N1tb.png

line 31 is inside ngAfterContentInit

line 27 is inside ngAfterContentChecked

CodePudding user response:

According to the documentation, native HTML elments are not supported as selector for ContentChild.

In this case, you have two options:

1. Use a template variable

You can add a template variable to the <header> HTML element and query for that variable:

<!-- app.component.html -->
<app-hook-cycles><header #header>...</header></app-hook-cycles>
/** hook-cycles.component.ts **/
@ContentChild("header")
public headerContent!: ElementRef;

see on stackblitz

2. Wrap the header into a custom component

You could create your own <app-header> component and query for that:

<!-- app.component.html -->
<app-hook-cycles><app-header>...</app-header></app-hook-cycles>
/** hook-cycles.component.ts **/
@ContentChild(HeaderComponent, { read: ElementRef })
public headerContent!: ElementRef;
  • Related