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 |
*ngIf | Conditional DOM rendering |
*ngFor | Looping over arrays or lists |
Comments
Post a Comment