I am trying to insert HTML code containing *ngIf and *ngFor directives via a DOM element’s innerHtml property. Is this possible?
I don’t understand how Angular renders things, so I don’t know how to go about doing this. I tried using Renderer2, but this did not help.
2
Answers
This is not possible as angular template need to be compiled and
innerHTML
passes directly the string to the dom element.The closest you can achieve but this is definitely not recommended : Create a component dynamically and pass your string as template.
This is not recommended as this requires to pull the
compiler
into the production bundle, which is heavy and also JIT components are less efficient.It looks like you need content projection, which is a way to pass HTML content (including Angular components and directives) from one component to another. Here is a quick content projection tutorial:
In the parent component:
And in the child component, add the following element:
The content in the "body" of
app-child-component
will be projected (like a "cut and paste" of the HTML) into theng-content
element in the template of the child component.