Search code examples
angulardata-bindinginnerhtmlviewchildelementref

InnerHtml of elementRef of component created dynamically by componentFacory not containing binded values


I have a simple component named component1: This is its HTML with the bindings and with the template reference:

<div class="AAA" [ngClass]="someClass" #templateRef > 
<div class="main-container"> <span> {{someNumber}}</span></div>
</div>

This is the component:

export class Component1Component implements OnInit { 

@ViewChild('templateRef ', { static: true })      
templateRef : ElementRef;
someNumber : number
someClass : string
get TemplateRef ()
{
   return this.templateRef ;
}

Now- In another component, I'm using ComponentFactoryService to create this component dynamically, and then set the 2 variables. I would like finally to get the HTML of the component after it is binded:

let componentFactory : ComponentFactory<any> = 
this.componentFactoryService.getComponentFacroty(this.componentName); //componentName is Component1Component 
this.componentRef = this.componentContainer.createComponent(componentFactory);
/*here I set the variables that should be binded*/
this.componentRef.instance.someNumber = 10;
this.componentRef.instance.someClass = "class1; 

Now I'm getting the innerHTML without the bindind although I can see these binding values in the component1Component oninit function.

var htmlAfterBindind = this.componentRef.instance.templateRef.nativeElement.innerHTML;

Solution

  • You need to make sure change detection has run on Component1Component before trying to access the rendered DOM.

    To do that, you can call ChangeDetectorRef.detectChanges before accessing the innerHTML:

    import { ChangeDetectorRef } from '@angular/core';
    
    constructor(private changeDetectorRef: ChangeDetectorRef) {}
    
    this.componentRef = this.componentContainer.createComponent(componentFactory);
    
    /*here I set the variables that should be binded*/
    this.componentRef.instance.someNumber = 10;
    this.componentRef.instance.someClass = "class1;
    
    /* Call detectChanges to render the DOM */
    this.changeDetectorRef.detectChanges();
    
    /* Now the DOM is ready */
    let htmlAfterBindind = this.componentRef.instance.templateRef.nativeElement.innerHTML;