I have a custom stuctural directive. It operates a lot like *ngIf, except that if a particular condition is true, it displays a specific, predetermined component which I'm calling DynamicComponent in the following, simplified example:
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input()
set myDirective(condition: Boolean) {
if (condition) {
const componentRef =
this.viewContainer.createComponent(DynamicComponent);
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
constructor(
private readonly templateRef: TemplateRef<unknown>,
private readonly viewContainer: ViewContainerRef) {}
}
To test this code, I need to access to instantiate it and then access the DynamicComponent instance. I have written the following test class, but it fails because @ViewChild fails to find DynamicComponent.
@Component({
selector: 'test-component',
template: `
<ng-container *myDirective="unused">
</ng-container>`,
})
class TestComponent {
// THIS DOES NOT FIND THE DynamicComponent!
@ViewChild(DynamicComponent, {static: false}) instance!: DynamicComponent;
}
How can I access DynamicComponent using an instance of TestComponent?