Code Reusability is the capacity to repurpose pre-existing code when developing new software applications. It will allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it. In this article, we will learn How to reuse template HTML blocks in Angular.
Steps for Installing & Configuring the Angular ApplicationStep 1: Create an Angular application using the following command.
ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname Project StructureIt will look like the following:
 Example 1: In this example, we will create a reuse a <h2> tag
HTML
<!-- app.component.html -->
<ng-template #MsgRef>
<h2 style="color: red">GeeksforGeeks</h2>
<br>
</ng-template>
<h2 style="color: green;">GeeksforGeeks</h2>
<h2>How to reuse template HTML block in Angular ?</h2>
<ng-template [ngTemplateOutlet]="MsgRef"></ng-template>
<ng-template [ngTemplateOutlet]="MsgRef"></ng-template>
<ng-template [ngTemplateOutlet]="MsgRef"></ng-template>
JavaScript
// app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: "./app.component.html",
styleUrls: ['./app.component.css']
})
export class AppComponent { }
JavaScript
// app.module.ts
import { NgModule }
from '@angular/core';
import { BrowserModule }
from '@angular/platform-browser';
import { HttpClientModule }
from '@angular/common/http';
import { AppComponent }
from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:

Example 2: In this example, we will reuse an image template.
HTML
<!-- app.component.html -->
<ng-template #MsgRef>
<img src=
"https://media.geeksforgeeks.org/wp-content/uploads/20231009182919/Angular-PrimeNG-copy.webp">
<br>
</ng-template>
<h2 style="color: green;">GeeksforGeeks</h2>
<h2>How to reuse template HTML block in Angular ?</h2>
<ng-template [ngTemplateOutlet]="MsgRef"></ng-template>
<ng-template [ngTemplateOutlet]="MsgRef"></ng-template>
<ng-template [ngTemplateOutlet]="MsgRef"></ng-template>
JavaScript
// app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: "./app.component.html",
styleUrls: ['./app.component.css']
})
export class AppComponent { }
JavaScript
// app.module.ts
import { NgModule }
from '@angular/core';
import { BrowserModule }
from '@angular/platform-browser';
import { HttpClientModule }
from '@angular/common/http';
import { AppComponent }
from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
|