Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Angular FAQ: Top Questions

5. What are Angular Directives?

In Angular, directives are special classes that allow developers to manipulate the DOM by adding behavior or modifying structure, appearance, or layout of HTML elements. They are an essential part of Angular’s powerful template system and enable developers to write expressive and dynamic views.

Angular categorizes directives into different types based on their purpose and how they interact with the DOM:

  • Structural Directives:
    • These directives modify the structure of the DOM by adding or removing elements.
    • Common examples include:
      • *ngIf – Conditionally includes or excludes an element.
      • *ngFor – Repeats an element for each item in a list.
      • *ngSwitch – Switches among multiple views based on a condition.
  • Attribute Directives:
    • These directives change the appearance or behavior of elements, components, or other directives.
    • Common examples include:
      • [ngStyle] – Binds inline CSS styles dynamically.
      • [ngClass] – Adds or removes CSS classes conditionally.
      • required, disabled, and custom directives.
  • Custom Directives:
    • Developers can create their own directives to encapsulate reusable logic or behaviors.
    • These custom directives can be structural or attribute-based depending on their use case.

// app.component.html

<div *ngIf="isVisible">Visible Content</div>

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

<div [ngStyle]="{ 'color': isImportant ? 'red' : 'black' }">
  Dynamic Style Example
</div>

<div [ngClass]="{ 'highlight': isHighlighted }">
  Conditional Class Example
</div>
        

Explanation of the Example Code:

  • *ngIf="isVisible": The element is rendered only if isVisible is true. It does not exist in the DOM if false.
  • *ngFor="let item of items": Repeats the <li> element for each item in the items array.
  • [ngStyle]: Dynamically applies inline styles based on a condition (e.g., red text if isImportant is true).
  • [ngClass]: Conditionally applies the highlight CSS class if isHighlighted is true.

Angular directives offer a powerful way to extend HTML with custom behavior and provide dynamic, conditionally rendered interfaces without deeply embedding logic into your templates.