Template Syntax in Angular

Template syntax is how Angular binds data and adds logic to your HTML. Let’s break down the essentials: interpolation ({{ }}), and structural directives like *ngIf and *ngFor.


๐Ÿงฉ Interpolation – {{ }}

Interpolation is used to display data from your component class in the template.

✅ Example:


<p>Hello, {{ name }}!</p>

export class AppComponent {
  name = 'Angular';
}

๐Ÿงฐ Structural Directives

Structural directives shape or change the structure of the DOM. They start with an asterisk *.


1. ๐Ÿงพ *ngIf – Conditional Rendering

Renders the element only if the condition is true.


<p *ngIf="isLoggedIn">Welcome back!</p>
<p *ngIf="!isLoggedIn">Please log in.</p>

isLoggedIn = true;

You can also use else:


<div *ngIf="items.length > 0; else noItems">
  <p>Items available!</p>
</div>
<ng-template #noItems>
  <p>No items found.</p>
</ng-template>

2. ๐Ÿ” *ngFor – Looping Over Data

Repeats an element for each item in a list.


<ul>
  <li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>

fruits = ['Apple', 'Banana', 'Cherry'];

With index:


<li *ngFor="let fruit of fruits; let i = index">
  {{ i + 1 }}. {{ fruit }}
</li>

๐Ÿ”„ Combine ngIf and ngFor

Avoid using both on the same element — instead, wrap ngFor inside an ng-container:


<ng-container *ngIf="fruits.length > 0">
  <li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ng-container>

๐Ÿง  Summary

Syntax Purpose
{{ value }}Data binding from TS to HTML
*ngIfConditional DOM rendering
*ngForLooping over arrays or lists

Comments

Popular posts from this blog

Car Wash System vb.net

Face recognition using EmguCV 3.0 and typing pattern recognition

Student Information System - AngularJS , ASP.NET API, C#