Imagine we have a html structure as follows
<div [innerHTML]="contentFromAPI | safeHTML"></div>
Now the content from the api would be a string consists of more HTML elements. Making the structure something like this:
<div>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
I want to create a component dynamically and insert it at the middle of the child nodes. In this case at the 5th place.
For this I’m doing something like this:
html file:
<div [innerHTML]="contentFromAPI | safeHTML" #articleContent></div>
ts file:
@ViewChild('articleContent', { read: ViewContainerRef })
private articleContent!: ViewContainerRef;
ngOnChanges(){
if(ads){
this.addElementToTemplate();
}
}
private addElementToTemplate() {
setTimeout(() => {
const childrenLength =
this.articleContent.element.nativeElement.children.length;
this.articleContent.createComponent(DynamicElement,{index: Math.ceil(childrenLength/2)});
}, 3000);
}
but this adds the component as a sibling to content element. Something like this:
<div>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
<dynamic-element></dynamic-element>
2
Answers
From What i understand form the question, here is solution which can be worked out in the .ts file.
hope this would helps 🙂
It is possible to insert an angular component inside
innerHTML
but we should note that elements inserted this way are outside angular context and change detection will not work, so it will behave like a normal HTML element. Its better you looks for alternative approaches and not usinginnerHTML
, Please find below example highlighting my point that change detection does not work inside innerHTMLfull code
Stackblitz Demo