Reusing Angular HTML code in the same component in 3 minutes, using templates.

Mahmoud Aburas
2 min readFeb 7, 2021

Say you have a specific part of your HTML code that you want to reuse multiple times in the same Component without repeating the code itself, something akin to this:

<div id="bubble-temp" class="bb-container">
<img class="bb-img" alt="bubbles" src="./assets/bubble.png"/>
<h5 class="bb-title">blub</h5>
<hr>
</div>
<!-- Show first -->
<div clone="bubble-temp"></div>
<!-- Show second -->
<div clone="bubble-temp"></div>
<!-- Show third -->
<div clone="bubble-temp"></div>

Well, if you’re using Angular then there’s a very simple solution to your problem, all you need to do is use <ng-template></ng-template> to contain your template code. This will let you reference the code from anywhere in your file, as many times as you like!

<ng-template #bubbleTemp>
<div class="bb-container">
<img class="bb-img" alt="bubbles" src="./assets/bubble.png"/>
<h5 class="bb-title">blub</h5>
<hr>
</div>
</ng-template>
<!-- Show first -->
<ng-template [ngTemplateOutlet]="bubbleTemp"></ng-template>
<!-- Show second -->
<ng-template [ngTemplateOutlet]="bubbleTemp"></ng-template>
<!-- Show third -->
<ng-template [ngTemplateOutlet]="bubbleTemp"></ng-template>

It’s that simple!
But… what if you want the data in the template to be controlled dynamically, for example inside an ngFor loop? all you need to do in that case is define a placeholder variable in the template declaration using the template’s let-varname syntax.

Then when you want to clone the template you pass the variables as an object using the context attribute:

<ng-template #bubbleTemp let-bubbledata>
<div class="bb-container">
<img class="bb-img" alt="bubbles" [src]="bubbledata.src"/>
<h5 class="bb-title">{{ bubbledata.title }}</h5>
<hr>
</div>
</ng-template>
<!-- Show first -->
<ng-template *ngTemplateOutlet="bubbleTemp; context: { $implicit: { title: 'first', src: 'assets/bluebubble.png' } }"></ng-template>
<!-- Show second -->
<ng-template *ngTemplateOutlet="bubbleTemp; context: { $implicit: { title: 'second', src: 'assets/redbubble.png' } }"></ng-template>
<!-- Show third -->
<ng-template *ngTemplateOutlet="bubbleTemp; context: { $implicit: { title: 'third', src: 'assets/greenbubble.png' } }"></ng-template>

Here $implicitsimply connects your data with the variable bubbleData , and you’re done :) this code should generate three bubble divs, each populated with the data you assigned to it.

Next time we’ll cover reusing the same code from entirely different components using the magic of templateRef! stay tuned…

--

--

Mahmoud Aburas

Just another code monkey, hit me up so we can chat about my most recent bug report, it’s _really_ weird.