Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda