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.' }
}
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.
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