Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add ng-template Dynamically

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.

like image 500
VISHAL TANK Avatar asked Feb 24 '26 22:02

VISHAL TANK


1 Answers

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

like image 87
Praveen Soni Avatar answered Feb 27 '26 01:02

Praveen Soni