Adding Dynamic Content inside <ng-template>

12.8k views Asked by At
 <ng-template #reuse>
  <div>Hello World</div>
</ng-template>

<ng-container [ngTemplateOutlet]="reuse"></ng-container>

<ng-container [ngTemplateOutlet]="reuse">
  <p>Good Morning</p>
</ng-container>

I would like to reuse the reuse template reference multiple times but with small modifications each time. In the above example, in the 2nd <ng-container> I would also like to add an additional <p> tag after the <div> tag (in the <ng-template>). Is it possible to achieve that without creating another template?

2

There are 2 answers

3
Joosep Parts On

What is the end goal here? When or how happens this "each time"? ng-template is never generated in html code, it generates it's contents as html at run time. So adding new html lines to a template is not possible. It is a dynamic abstraction of Angular syntax.

However you could use template variables to pre-configure the template to add new lines when themplate bound variables change.

For example, you could add more template variables by adding let to ng-template. https://angular.io/guide/template-reference-variables#template-input-variable

<div *ngFor="let day of Weekdays"> 
<ng-container *ngIf = 
    "(day == 'Saturday' || day == 'Sunday'); else elseTemplate"> 
  <h1>{{day}} is a weekend</h1> 
</ng-container> 
<ng-template #elseTemplate> 
  <h1>{{day}} is not a weekend</h1> 
</ng-template> 
</div> 
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular 6';
  Weekdays: Array = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
  ];
}

Example: https://stackblitz.com/edit/hello-angular-6-ng-template-and-ng-container-exam-w2zn1j?file=src%2Fapp%2Fapp.component.html

4
Chris Hamilton On

Yes, you can pass a context object to your template with [ngTemplateOutletContext] or the shorthand with *ngTemplateOutlet. Then you can render things based on that context.

<ng-template #reuse let-message="message">
  <div>Hello World</div>
  <p *ngIf="message">{{ message }}</p>
</ng-template>

<ng-container [ngTemplateOutlet]="reuse"></ng-container>

<ng-container
  [ngTemplateOutlet]="reuse"
  [ngTemplateOutletContext]="{ message: 'Good Morning' }"
></ng-container>

or

<ng-template #reuse let-message="message">
  <div>Hello World</div>
  <p *ngIf="message">{{ message }}</p>
</ng-template>

<ng-container *ngTemplateOutlet="reuse"></ng-container>

<ng-container
  *ngTemplateOutlet="reuse; context: { message: 'Good Morning' }"
></ng-container>

Doc reference: https://angular.io/api/common/NgTemplateOutlet