Loading

Templates

  • At the core of Angular lies its templating system, a robust mechanism for crafting dynamic views. 
  • Angular templates are the backbone of this system, providing a seamless bridge between the application logic and what users perceive.

Example:

Step 1: Create an Angular project using Angular CLI.

ng new Angular

Step 2: Create a new component named ‘list’

ng g c list

Step 3: Now use the ng-template in the ‘list.component.html’.

<h2>List Component</h2>

<ul>
  <ng-container *ngFor="let item of items">
    <!-- Use ng-template for the list item -->
    <ng-template [ngIf]="item.isVisible" [ngIfElse]="hiddenTemplate">
      <li>{{ item.name }}</li>
    </ng-template>
  </ng-container>
</ul>

<!-- Define the ng-template for hidden items -->
<ng-template #hiddenTemplate>
  <li style="color: gray;">This item is hidden</li>
</ng-template>

Step 4: Edit the 'list.component.ts' to define the item list.

import { Component, OnInit } 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 }
  ]

}
}

Step 5: Add the ‘<app-list></app-list>’ to the ‘app.component.html’ to include the ‘List-Component’ in the main application.

<h1>Angular Template Example</h1>
<app-list></app-list>

Step 6: Now run or compile the application.

ng serve

You will see the result on http://localhost:4200