Skip to content

Chapter 1.3 Directives in Angular – Structural (*ngIf, *ngFor), Attribute ([ngClass], [ngStyle]), Custom Directives

Introduction

Directives in Angular are powerful tools that allow developers to manipulate the DOM dynamically. There are three types of directives:

  1. Structural Directives – Modify the DOM layout by adding or removing elements (*ngIf, *ngFor).
  2. Attribute Directives – Modify the appearance or behavior of an element ([ngClass], [ngStyle]).
  3. Custom Directives – User-defined directives to extend Angular’s functionality.

1. Structural Directives

Structural directives are prefixed with an asterisk (*) and are responsible for altering the structure of the DOM.

1.1 *ngIf – Conditional Rendering

*ngIf adds or removes an element from the DOM based on a condition.

Example:

export class AppComponent {
  isVisible: boolean = true;
}
<button (click)="isVisible = !isVisible">Toggle</button>
<p *ngIf="isVisible">This text is conditionally rendered.</p>

Note: When false, *ngIf removes the element completely from the DOM, improving performance.


1.2 *ngFor – Looping Through Items

*ngFor is used to iterate over an array and dynamically generate elements.

Example:

export class AppComponent {
  items = ['Apple', 'Banana', 'Cherry'];
}
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

Key Consideration: Use trackBy to optimize performance when dealing with large lists.

<li *ngFor="let item of items; trackBy: trackByFn">{{ item }}</li>
trackByFn(index: number, item: string) {
  return index; // Or return a unique ID if available
}

2. Attribute Directives

Attribute directives modify the behavior or appearance of an element.

2.1 [ngClass] – Dynamically Apply CSS Classes

[ngClass] allows binding multiple CSS classes based on conditions.

Example:

export class AppComponent {
  isActive = true;
}
<p [ngClass]="{ 'active': isActive, 'inactive': !isActive }">Styled Text</p>
.active { color: green; }
.inactive { color: red; }

2.2 [ngStyle] – Dynamic Inline Styles

[ngStyle] binds styles dynamically based on component properties.

Example:

export class AppComponent {
  textColor = 'blue';
  fontSize = '20px';
}
<p [ngStyle]="{ 'color': textColor, 'font-size': fontSize }">Styled Text</p>

3. Custom Directives

Custom directives allow developers to create reusable behaviors.

3.1 Creating a Custom Directive

A custom directive modifies element behavior and can be used like built-in directives.

Steps to Create a Custom Directive:

  1. Generate a directive using Angular CLI: ng generate directive highlight
  2. Modify the directive (highlight.directive.ts):
import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}
  1. Use the directive in a template:
<p appHighlight>Hover over me!</p>

Angular Interview Questions & Answers

Q1. What are Directives in Angular?

Answer: Directives are instructions that tell Angular how to modify the DOM. They can be structural, attribute-based, or custom.

Q2. How does *ngIf work in Angular?

Answer: *ngIf conditionally adds or removes elements from the DOM based on a boolean expression.

Q3. What is the difference between *ngIf and [hidden]?

Answer:

  • *ngIf completely removes the element from the DOM when false.
  • [hidden] only hides the element using CSS (display: none).

Q4. What is *ngFor used for?

Answer: *ngFor is a structural directive that loops over an array and generates dynamic elements.

Q5. Why use trackBy in *ngFor?

Answer: trackBy improves performance by uniquely identifying elements, preventing unnecessary re-renders.

Q6. What is the difference between [ngClass] and [ngStyle]?

Answer:

  • [ngClass] is used for applying multiple CSS classes dynamically.
  • [ngStyle] is used for applying inline styles dynamically.

Q7. How do you create a custom directive in Angular?

Answer: You can create a custom directive using @Directive and modifying the behavior of an element using ElementRef and HostListener.


Conclusion

Directives are a powerful feature in Angular that enhance the flexibility of applications. Understanding structural directives (*ngIf, *ngFor), attribute directives ([ngClass], [ngStyle]), and custom directives helps in building dynamic, reusable, and optimized Angular applications.

Stay tuned for more Angular tutorials! 🚀

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *