3

I want to add below content dynamically in HTML.

<ng-template #elseblock *ngIf="var">
    <h1>
        {{heading}}
    </h1>
</ng-template>

I am using below approch for this.

In app.component.ts file :

htmldata: any = `<ng-template #elseComponent *ngIf="var">
<h1>
  {{ heading }}
</h1>

`;

and in app.component.html

 <div [innerHTML]="htmldata"> </div>

but this approch only render h1 tag in the DOM.(no ng-template)

Please help me to add ng-template dynamically so that #else block, *ngIf will also work.

1

1 Answer 1

1

As Per My Understanding from your question, you want to do content projection.

you should use template outlet for this type of usecase.

<ng-template #heading let-heading>
  <h1>
    {{heading}}
  </h1>
</ng-template>


<ng-container *ngTemplateOutlet="heading; context: ContextObj">
</ng-container>

official Angular doc ngTemplateOutlet
or a great blog post on ngTemplateOutlet

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.