Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
How can I use ViewChild to find a dynamically created component

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!