Search code examples
javascriptangulartypescriptangular13

InnerHTML has no property data when using viewContainerRef.createComponent() and then adding data


Problem - I'm passing a ViewContainerRef into my constructor to instantiate a component named 'MemberCardComponent'. Then I'm trying to fill it with input data, but no data is being populated into the innerHTML.

Stackblitz - I've setup this SB demonstrate my issue: Stackblitz link

const component = this.viewContainerRef.createComponent(MemberCardComponent);
component.instance.MemberCard = memberData; // memberData fetched from Db
const memberCardHtml = component.location.nativeElement.innerHTML; // innterHTML doesn't have MemberCard data.

MemberCard is an input property that looks like this:

@Input() set MemberCard(member: IMemberCard) {
    this.member = member;
}

I see the inner html isn't filled with any of the data. All the fields are empty, where there should be member data. Ex. photoUrl, name, etc

QUESTION - Is there some other action I need to perform to get my input data into the innerHTML?

Here is what I see when I hover over the innerHtml. enter image description here

'<div _ngcontent-yft-c87="" class="card"><div _ngcontent-yft-c87="" class="row g-0 row-eq-height"><div _ngcontent-yft-c87="" class="col-md-4"><picture _ngcontent-yft-c87=""><source _ngcontent-yft-c87="" media="(min-width: 0px) and (max-width: 350px)"><source _ngcontent-yft-c87="" media="(min-width: 351px) and (max-width: 720px)"><source _ngcontent-yft-c87="" media="(min-width: 721px) and (max-width: 1001px)"><source _ngcontent-yft-c87="" media="(min-width: 1002px)"><img _ngcontent-yft-c87="" alt…"float-end"></span></div><div _ngcontent-yft-c87="" class="col-12"><span _ngcontent-yft-c87="">Experience</span><span _ngcontent-yft-c87="" class="float-end"></span></div><div _ngcontent-yft-c87="" class="col-12"><span _ngcontent-yft-c87=""></span><span _ngcontent-yft-c87="" class="float-end"></span></div><div _ngcontent-yft-c87="" class="col-12"><span _ngcontent-yft-c87="">Education</span><span _ngcontent-yft-c87="" class="float-end"></span></div></div></div></div></div><!--container--></div>'

FYI - I'm trying to create the string representation of the component to populate a swiper.js slide. Here is another SO post I created that explains why I need the string representation of my component.


Solution

  • You can inject ChangeDetectionRef to MemberCardComponent component and then call detectChanges() in your parent component.

    You are trying to get the innerHtml before the change detection is triggered.

    here is a working example: Stackblitz