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:

  • ngIf
  • ngFor
  • ngSwitch
  • ngClass
  • ngStyle

ngIf Directive

The ngIf directive is used to conditionally include or exclude an element in the DOM based on a boolean expression.

Syntax

<div *ngIf="condition">Content to display if condition is true</div>

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 *ngIf directive checks the value of isVisible.
  • If isVisible is true, the <div> element is included in the DOM.
  • The button toggles the value of isVisible when clicked.

ngFor Directive

The ngFor directive is used to repeat a portion of the DOM tree for each item in a list.

Syntax

<div *ngFor="let item of items">{{ item }}</div>

Example

<!-- app.component.html -->
<ul>
  <li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>
// 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 *ngFor directive iterates over the fruits array.
  • 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 the selectedFruit expression.
  • The *ngSwitchCase directives display content based on the value of selectedFruit.
  • The *ngSwitchDefault directive 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

<div [ngClass]="{'class-name': condition}">Content</div>

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;
  }
}
/* app.component.css */
.highlight {
  background-color: yellow;
}

Explanation

  • The [ngClass] directive adds the highlight class if isHighlighted is true.
  • The button toggles the value of isHighlighted when clicked.

ngStyle Directive

The ngStyle directive is used to dynamically set inline styles based on an expression.

Syntax

<div [ngStyle]="{'style-name': value}">Content</div>

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 the color style based on the value of textColor.
  • The button toggles the value of textColor between black and blue when clicked.

Summary

In this section, we covered some of the most commonly used built-in directives in Angular:

  • ngIf for conditional rendering.
  • ngFor for iterating over a list.
  • ngSwitch for conditional display based on matching expressions.
  • ngClass for dynamically adding or removing CSS classes.
  • ngStyle for 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.

© Copyright 2024. All rights reserved