angularangular2-directivesangular2-components

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.


Solution

  • 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