Directives in Angular

In Angular, directives are classes that add behavior to elements in the DOM. There are two main types:

  1. Structural Directives – change the DOM structure (add/remove elements).
    • Examples: *ngIf, *ngFor.
  2. Attribute Directives – change the appearance or behavior of an element.
    • Examples: [ngClass], [ngStyle].

1. Structural Directives

*ngIf

Conditionally renders elements.

<p *ngIf="isLoggedIn">
  Welcome, user!
</p>

*ngFor

Loops over an array to render multiple elements.

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

2. Attribute Directives

[ngClass]

Dynamically adds or removes CSS classes.

<p [ngClass]="{ 'highlighted': isSpecial }">
  This text may be highlighted.
</p>

[ngStyle]

Dynamically applies inline styles.

<p [ngStyle]="{ 'color': isRed ? 'red' : 'blue' }">
  This text changes color dynamically.
</p>

3. Full Example Combining All

Component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  showList = true;
  items = ['Apple', 'Banana', 'Cherry'];
  highlight = true;
  isRed = true;
}

Template

<h2>Angular Directives Demo</h2>

<!-- Structural Directive -->
<p *ngIf="showList">Here is a list of fruits:</p>

<!-- Loop with Attribute Directives -->
<ul>
  <li *ngFor="let item of items"
      [ngClass]="{ 'highlighted': highlight }"
      [ngStyle]="{ 'color': isRed ? 'red' : 'blue' }">
    {{ item }}
  </li>
</ul>

<!-- Buttons to toggle -->
<button (click)="showList = !showList">Toggle List</button>
<button (click)="highlight = !highlight">Toggle Highlight</button>
<button (click)="isRed = !isRed">Toggle Color</button>

Styles

.highlighted {
  font-weight: bold;
}

🔹 Explanation

  • *ngIf → Shows/hides the paragraph.
  • *ngFor → Loops over the items array.
  • [ngClass] → Adds the highlighted class dynamically.
  • [ngStyle] → Changes text color dynamically.

This example demonstrates how structural and attribute directives work together to create dynamic, interactive Angular templates.

Leave a Reply