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