Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic data in ng-template

I'm relatively new to Angular and struggling to figure out how to pass a string into a template. I would like to create a reusable template (or component) that will display some instruction information on how to proceed with an action.

Currently I'm achieving this by doing the following:

<div *ngIf="foo; else noFoo">
  <!-- Show things -->
</div>

<div *ngIf="bar; else noBar">
  <!-- Show things -->
</div>

<ng-template #noFoo>
  <div class="message">
    <h4>No Foo</h4>
    <p>Please do foo to continue.</p>
  </div>
</ng-template>

<ng-template #noBar>
  <div class="message">
    <h4>No Bar</h4>
    <p>Please do bar to continue.</p>
  </div>
</ng-template>

While this is working fine, it results in quite a few templates with very similar code. Instead I would like to do something like:

<div *ngIf="foo; else showMessage">
  <!-- Show things -->
</div>

<div *ngIf="bar; else showMessage">
  <!-- Show things -->
</div>

<ng-template #showMessage>
  <div class="message">
    <h4>{{ heading }}</h4> <!-- get dynamic heading -->
    <p>{{ message }}</p> <!-- get dynamic message -->
  </div>
<ng-template>

A nudge in the right direction would be greatly appreciated. Thanks!

Solution

I was able to use the answer provided to create the following:

Template:

<ng-container *ngIf="!foo; showFoo">
  <ng-container *ngTemplateOutlet="showMessage; context: messages.noFoo"></ng-container>
</ng-container>

<ng-template #showMessage let-heading="heading" let-message="message">
  <div class="message">
    <h4>{{ heading }}</h4>
    <p>{{ message }}</p>
  </div>
</ng-template>

Component:

public messages: any = {
  noFoo: { heading: 'No Foo', message: 'Please do foo to continue.' },
  noBar: { heading: 'No Bar', message: 'Please do bar to continue.' }
}
like image 207
Hughes Avatar asked Apr 30 '26 11:04

Hughes


1 Answers

Use ngTemplateOutletContext. This lets you pass a parameter or variable into a template to be used.

Documentation here => https://angular.io/api/common/NgTemplateOutlet

I have used this to create a lot of elements that act and look similar, but needed a few things modified between them.

like image 117
Chris Reed Avatar answered May 03 '26 23:05

Chris Reed