Introduction
Directives are a core feature of Angular that allow you to attach behavior to elements in the DOM. Built-in directives are provided by Angular to help you manipulate the DOM easily. In this section, we will cover some of the most commonly used built-in directives, including:
ngIfngForngSwitchngClassngStyle
ngIf Directive
The ngIf directive is used to conditionally include or exclude an element in the DOM based on a boolean expression.
Syntax
Example
<!-- app.component.html --> <div *ngIf="isVisible">This text is visible only if isVisible is true.</div> <button (click)="toggleVisibility()">Toggle Visibility</button>
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isVisible = true;
toggleVisibility() {
this.isVisible = !this.isVisible;
}
}Explanation
- The
*ngIfdirective checks the value ofisVisible. - If
isVisibleistrue, the<div>element is included in the DOM. - The button toggles the value of
isVisiblewhen clicked.
ngFor Directive
The ngFor directive is used to repeat a portion of the DOM tree for each item in a list.
Syntax
Example
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
fruits = ['Apple', 'Banana', 'Cherry'];
}Explanation
- The
*ngFordirective iterates over thefruitsarray. - For each item in the array, a
<li>element is created and the item is displayed.
ngSwitch Directive
The ngSwitch directive is used to conditionally display one of several elements based on a matching expression.
Syntax
<div [ngSwitch]="expression"> <div *ngSwitchCase="case1">Case 1</div> <div *ngSwitchCase="case2">Case 2</div> <div *ngSwitchDefault>Default Case</div> </div>
Example
<!-- app.component.html -->
<div [ngSwitch]="selectedFruit">
<div *ngSwitchCase="'Apple'">You selected Apple.</div>
<div *ngSwitchCase="'Banana'">You selected Banana.</div>
<div *ngSwitchDefault>Select a fruit.</div>
</div>
<button (click)="selectFruit('Apple')">Apple</button>
<button (click)="selectFruit('Banana')">Banana</button>
<button (click)="selectFruit('')">None</button>// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedFruit = '';
selectFruit(fruit: string) {
this.selectedFruit = fruit;
}
}Explanation
- The
[ngSwitch]directive evaluates theselectedFruitexpression. - The
*ngSwitchCasedirectives display content based on the value ofselectedFruit. - The
*ngSwitchDefaultdirective displays content if no case matches.
ngClass Directive
The ngClass directive is used to dynamically add or remove CSS classes based on an expression.
Syntax
Example
<!-- app.component.html -->
<div [ngClass]="{'highlight': isHighlighted}">This text can be highlighted.</div>
<button (click)="toggleHighlight()">Toggle Highlight</button>// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isHighlighted = false;
toggleHighlight() {
this.isHighlighted = !this.isHighlighted;
}
}Explanation
- The
[ngClass]directive adds thehighlightclass ifisHighlightedistrue. - The button toggles the value of
isHighlightedwhen clicked.
ngStyle Directive
The ngStyle directive is used to dynamically set inline styles based on an expression.
Syntax
Example
<!-- app.component.html -->
<div [ngStyle]="{'color': textColor}">This text changes color.</div>
<button (click)="changeColor()">Change Color</button>// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
textColor = 'black';
changeColor() {
this.textColor = this.textColor === 'black' ? 'blue' : 'black';
}
}Explanation
- The
[ngStyle]directive sets thecolorstyle based on the value oftextColor. - The button toggles the value of
textColorbetweenblackandbluewhen clicked.
Summary
In this section, we covered some of the most commonly used built-in directives in Angular:
ngIffor conditional rendering.ngForfor iterating over a list.ngSwitchfor conditional display based on matching expressions.ngClassfor dynamically adding or removing CSS classes.ngStylefor dynamically setting inline styles.
Understanding these directives is crucial for manipulating the DOM effectively in Angular applications. In the next section, we will explore how to create custom directives to extend Angular's capabilities further.
Angular 2+ Course
Module 1: Introduction to Angular
Module 2: TypeScript Basics
- Introduction to TypeScript
- TypeScript Variables and Data Types
- Functions and Arrow Functions
- Classes and Interfaces
