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

178
Views
How to wait that ngAfterViewInit() runs while creating instance of a component from a directive?

I have a directive that is creating in code an instance of component template he uses and set its innerHTml, which will change the tempalte dimension:

  var factory = this.resolver.resolveComponentFactory(MyComponentTemplate);
  this.templateComponent = this.viewContainerRef.createComponent(factory);

  this.templateComponent.instance.htmlStr = anyText;

Now, here is the problem. At this stage I will get undefined on the component sizes:

console.log(this.templateComponent.instance.width);    //undefined
console.log(this.templateComponent.instance.height);   //undefined

In debug I noticed that only after my component runs ngAfterViewInit(), only then I can read the component template width and height from my directive and use that values.

Is there a way I can tell my directive to wait until ngAfterViewInit() ends, and than do what I need from my directive with that info I'm looking for.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

constructor(private cdRef:ChangeDetectorRef) {}

...

  var factory = this.resolver.resolveComponentFactory(MyComponentTemplate);
  this.templateComponent = this.viewContainerRef.createComponent(factory);
  this.templateComponent.instance.htmlStr = anyText;

  this.cdRef.detectChanges(); // run change detection immediately

  console.log(this.templateComponent.instance.width);    //undefined
  console.log(this.templateComponent.instance.height);   //undefined
about 4 years ago · Santiago Trujillo Report

0

Using a globally injected ChangeDetectorRef isn't necessary and may not work. You can rely on the ComponentRef's changeDetectorRef method :

var factory = this.resolver.resolveComponentFactory(MyComponentTemplate);
this.templateComponent = this.viewContainerRef.createComponent(factory);
this.templateComponent.instance.htmlStr = anyText;

this.templateComponent.changeDetectorRef.detectChanges();
about 4 years ago · Santiago Trujillo Report
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!