79209277

Date: 2024-11-20 23:58:17
Score: 0.5
Natty:
Report link

Angular 18

Using @ViewChildren in an attribute directive does not work because attribute directives don't have templates, so there are no children to query. You need to use @ContentChildren instead. Make sure to set descendants equal to true if the component you want to select isn't a direct descendant of the element with the attribute directive.

import { AfterViewInit, Directive, QueryList, ContentChildren } from '@angular/core';
import { TargetComponent } from './target.component';

@Directive({
  selector: '[appSubject]',
  standalone: true,
})
export class SubjectDirective implements AfterViewInit {
  @ContentChildren(TargetComponent, { descendants: true }) targets!: QueryList<TargetComponent>;

  ngAfterViewInit(): void {
    console.log('targets = ');
    console.log(this.targets);
  }
}

Additional context: https://github.com/angular/angular/issues/58642

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Shaddy Zeineddine