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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With