Reusing template HTML blocks can significantly improve code readability in a component.
Creating a new component is the most common way tackle code duplication, but sometimes you only need some local markup to be repeated. In this post, we’ll use ng-template
to reuse template HTML blocks this in Angular.
Understanding ng-template
ng-template
is an Angular directive that defines a template block without rendering it immediately. It serves as a placeholder for content that can be dynamically loaded or reused.
Creating a reusable template
Start by defining your HTML block within an ng-template directive:
<ng-template #myTemplate>
<div class="container">
<h1>Welcome to My Website</h1>
<p>Discover amazing content!</p>
</div>
</ng-template>
Code language: HTML, XML (xml)
Reuse the template
You can reuse it wherever needed using the ng-container
directive. This directive doesn’t create an additional element in the DOM, which makes it ideal for structural purposes.
<ng-container *ngTemplateOutlet="myTemplate"></ng-container>
Code language: HTML, XML (xml)
Customising the template
ng-template
also allows you to pass data to customise the template block. You can achieve this by using template variables and ngTemplateOutletContext
.
<ng-template #myTemplate let-title let-content="content">
<div class="container">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
</ng-template>
<ng-container *ngTemplateOutlet="myTemplate; context: { $implicit: 'Custom Title', content: 'Custom Content' }">
</ng-container>
Code language: HTML, XML (xml)
In conclusion, ng-template
is a powerful directive in Angular for reusing HTML blocks. If you can’t justify creating a new component for a few lines of repeated HTML, you can reuse template HTML blocks using these steps.