skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    <app-child-component>
      This is custom content with directives:
      <p *ngIf="display"> Conditional paragraph</p>
    </app-child-component>
    

    And in the child component, add the following element:

    <ng-content></ng-content>
    

    The content in the "body" of app-child-component will be projected (like a "cut and paste" of the HTML) into the ng-content element in the template of the child component.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search