0

QueryList of child directives remains undefined in ngAfterViewInit lifecycle hook.

What i'm I missing? Here my code:

app.component.html

<main appDirOne>
  <p appDirTwo>Main content</p>
  <p appDirTwo>Main content</p>
  <p appDirTwo>Main content</p>
  <p appDirTwo>Main content</p>
</main>

child directive dir-two.directive.ts

import { Directive } from '@angular/core';

@Directive({
  selector: '[appDirTwo]'
})
export class DirTwoDirective {

  constructor() { 
    console.log(Math.random())
  }

}

parent directive dir-one.directive.ts

    import {
      AfterViewInit,
      Directive,
      QueryList,
      ViewChildren,
    } from '@angular/core';
    import { DirTwoDirective } from './dir-two.directive';
    
    @Directive({
      selector: '[appDirOne]',
    })
    export class DirOneDirective implements AfterViewInit {
      @ViewChildren(DirTwoDirective) childDirectives: QueryList<DirTwoDirective>;
      constructor() {}
    
      ngAfterViewInit() {
        console.log(this.childDirectives); // <--- still undefined here
      }
    }

stackblitz example

Sam L
  • 1

1 Answers1

1

Directives do not have a view, so you cannot use @ViewChild / @ViewChildren.

In your case however you could use @ContentChildren:

@Directive({
  selector: '[appDirOne]',
})
export class DirOneDirective implements AfterViewInit {
  @ContentChildren(DirTwoDirective) childDirectives: QueryList<DirTwoDirective>;
  constructor() {}

  ngAfterViewInit() {
    console.log(this.childDirectives); // <--- should be there now ;)
  }
}

Updated blitz

Sébastien
  • 11,860
  • 11
  • 58
  • 78