How to reuse template HTML block in Angular ?
Last Updated :
07 Dec, 2023
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 Application
Step 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 Structure
It will look like the following:
Example 1: In this example, we will create a reuse a <h2> tag
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
import { Component, OnInit } from '@angular/core' ;
@Component({
selector: 'app-root' ,
templateUrl: "./app.component.html" ,
styleUrls: [ './app.component.css' ]
})
export class AppComponent { }
|
Javascript
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
< ng-template #MsgRef>
< img src =
< 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
import { Component, OnInit } from '@angular/core' ;
@Component({
selector: 'app-root' ,
templateUrl: "./app.component.html" ,
styleUrls: [ './app.component.css' ]
})
export class AppComponent { }
|
Javascript
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:
Share your thoughts in the comments
Please Login to comment...