Angular Tutorial
Angular Directives (*ngIf, *ngFor)
Directives in Angular are classes that add extra, custom behavior to elements in your HTML DOM. If Components are the building blocks, Directives are the tools used to manipulate them conditionally or repeatedly. There are two main types of Directives you will use daily: Structural and Attribute.
Structural Directives (ngIf, ngFor, ngSwitch)
Structural directives fundamentally change the structure of the DOM. They literally add, remove, or replace elements from the page entirely. Structural directives always begin with an asterisk (*).
1. *ngIf
Used to conditionally render an element. If the condition is false, the element is completely erased from the DOM (not just hidden with CSS).
<div *ngIf="isLoggedIn; else loggedOutBlock">
<h1>Welcome to your Dashboard!</h1>
</div>
<ng-template #loggedOutBlock>
<h1>Please log in.</h1>
</ng-template>2. *ngFor
Used to loop over an array of data and stamp out an HTML element for every single item in the array.
<ul>
<li *ngFor="let user of userList; let i = index">
{{ i + 1 }}. {{ user.name }}
</li>
</ul>Attribute Directives (ngClass, ngStyle)
Unlike structural directives, Attribute directives do not remove or add elements. Instead, they dynamically change the appearance or behavior of an existing element.
1. [ngClass]
Allows you to dynamically add or remove CSS classes based on logical conditions in your TypeScript class.
<!-- If isHighlighted is true, the 'bg-warning' class is applied -->
<div [ngClass]="{ 'bg-warning': isHighlighted, 'text-dark': true }">
This box changes colors dynamically!
</div>2. [ngStyle]
Similar to ngClass, but applies inline styling directly.
<p [ngStyle]="{ 'font-size': isLarge ? '24px' : '14px', 'color': textColor }">
This text manipulates its inline attributes.
</p>Control Flow System (Angular 17+)
It is highly important to note that Angular v17 introduced a revolutionary new built-in syntax that replaces *ngIf and *ngFor. It is highly recommended for modern applications:
@if (isLoggedIn) {
<h1>Welcome back!</h1>
} @else {
<h1>Log In</h1>
}
@for (user of userList; track user.id) {
<li>{{ user.name }}</li>
}Conclusion
Directives allow you to write complex, logical HTML templates that respond to data instantly. Next, we will look at how we can instantly format data directly within our templates using Pipes.