Templates
At the heart of every Angular application is the template system.
Templates are like the blueprint that tells Angular how to display your data and UI.
They act as a bridge between your applications logic and what users see on the screen, making your app dynamic and interactive.
They act as a bridge between your applications logic and what users see on the screen, making your app dynamic and interactive.
What Is a Template ?
A template in Angular is usually an HTML file (e.g., list.component.html) that contains
A template in Angular is usually an HTML file (e.g., list.component.html) that contains
- Standard HTML elements
- Angulars special syntax like *ngFor, *ngIf, {{ }} for data binding, and more
Example: Using ng-template in Angular
Step 1: Create a New Angular Project
ng new Angular
Step 2: Create a List Component
ng g c list
This creates files like:
Step 3: Add Template Logic with ng-template
Edit list.component.html
- list.component.ts
- list.component.html
Step 3: Add Template Logic with ng-template
Edit list.component.html
<h2>List Component</h2>
<ul> <ng-container *ngFor="let item of items"> <!-- Use ng-template to decide what to display --> <ng-template [ngIf]="item.isVisible" [ngIfElse]="hiddenTemplate"> <li>{{ item.name }}</li> </ng-template> </ng-container></ul>
<!-- Template shown when item is hidden --><ng-template #hiddenTemplate> <li style="color: gray;">This item is hidden</li></ng-template>
- *ngFor repeats content for each item in the list.
- ngIf decides whether to show the real item or the hidden message.
Step 4: Define Data in the Component
Edit list.component.ts
import { Component } from '@angular/core';
@Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.css']})export class ListComponent { items = [ { name: 'Sugar', isVisible: true }, { name: 'Flour', isVisible: false }, { name: 'Oil', isVisible: false }, { name: 'Spices', isVisible: true } ];}
Now, you have a list of items, each with an isVisible property.
Step 5: Display the Component in App
Edit app.component.html
<h1>Angular Template Example</h1><app-list></app-list>
Step 6: Run Your App
ng serve
Open your browser at:
http://localhost:4200
You will see
- “Sugar” and “Spices” as normal items
- “Flour” and “Oil” shown as “This item is hidden” in gray