I have been working on a test component that includes an example of two directives, with one being used as an attribute directive. I am utilizing the ViewChild decorator to access these directives in the ngAfterViewInit handler. However, when I try to retrieve the ViewChild for each directive, it returns undefined. Oddly enough, when inspecting the page, the directives are clearly present in the DOM.
If you want to take a look at the issue, here is a StackBlitz example: https://stackblitz.com/edit/stackblitz-starters-f3g4sv?file=src%2Ftest.component.ts
Below is the code snippet for the test component:
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
QueryList,
ViewChild,
ViewChildren,
ViewEncapsulation,
} from '@angular/core';
import { CommonModule } from '@common';
import { TestContainerDirective } from './test-container.directive';
import { OtherContainerDirective } from './other-test-container.directive';
@Component({
selector: 'app-test',
standalone: true,
imports: [CommonModule, OtherContainerDirective],
templateUrl: './test.html',
styleUrl: './test.scss',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppTestComponent implements AfterViewInit {
@ViewChild(TestContainerDirective)
public _testContainerRef!: TestContainerDirective;
@ViewChild(OtherContainerDirective)
public _otherContainerRef!: OtherContainerDirective;
@ViewChildren(TestContainerDirective)
_testContainerChildren!: QueryList<TestContainerDirective>;
constructor() {}
public ngAfterViewInit(): void {
console.log('_testContainerRef', this._testContainerRef);
console.log('_otherContainerRef', this._testContainerRef);
console.log('_testContainerChildren', this._testContainerChildren);
setTimeout(() => {
console.log('_testContainerRef', this._testContainerRef);
console.log('_otherContainerRef', this._testContainerRef);
}, 0);
}
}
The template for this test component looks like this:
<p>This is the test component</p>
<span>
Open the console and look for the references to the directives below
</span>
<p></p>
<div appTestContainer>test container</div>
<other-container>other container</other-container>
Lastly, let's not forget about the test directives themselves:
@Directive({
standalone: true,
selector: '[appTestContainer]',
})
export class TestContainerDirective {
constructor(public viewContainer: ViewContainerRef) {}
}
@Directive({
standalone: true,
selector: 'other-container',
})
export class OtherContainerDirective {
constructor(public viewContainer: ViewContainerRef) {}
}
It's strange that despite following the approach outlined in the documentation, I'm still encountering this issue. Any insights or assistance would be greatly appreciated!