Angular Attribute vs Structural Directives

Learn the differences between Angular Attribute Directives and Structural Directives with architecture diagrams, lifecycle, built-in directives, custom directives, Angular 17 control flow, enterprise examples, best practices, and interview questions.

Angular Directives are one of the most powerful features of the framework. They allow developers to extend HTML by changing the appearance, behavior, or structure of DOM elements.

Angular provides two major categories of directives:

  • Attribute Directives – Change the appearance or behavior of existing elements.
  • Structural Directives – Change the DOM structure by adding or removing elements.

Understanding the difference between these two directive types is a common Angular interview topic and is essential for writing scalable Angular applications.


Table of Contents

  • What are Angular Directives?
  • Types of Directives
  • Attribute Directives
  • Structural Directives
  • Key Differences
  • Built-in Directives
  • Custom Directives
  • Angular 17 Control Flow
  • Performance Considerations
  • Enterprise Example
  • Best Practices
  • Top 10 Interview Questions
  • Summary

What are Angular Directives?

A Directive is a class that adds additional behavior to DOM elements.

Angular has three directive categories:

Directive Type Purpose
Component Directive with a template
Attribute Directive Changes appearance or behavior
Structural Directive Changes DOM structure

Angular Directive Architecture

flowchart TD

Angular

Angular --> Components

Angular --> AttributeDirectives

Angular --> StructuralDirectives

Components --> DOM

AttributeDirectives --> DOM

StructuralDirectives --> DOM

Attribute Directives

Attribute Directives modify the behavior or appearance of an existing DOM element without adding or removing it.

Examples:

  • ngClass
  • ngStyle
  • ngModel

They keep the element in the DOM.


Attribute Directive Flow

flowchart LR

Component

Component --> AttributeDirective

AttributeDirective --> ExistingDOM

ExistingDOM --> Browser

ngClass Example

isActive = true;
<div

[ngClass]="{'active': isActive}">

Angular

</div>

Result

Adds CSS class "active"

ngStyle Example

textColor = 'blue';
<p

[ngStyle]="{'color': textColor}">

Hello Angular

</p>

Result

Changes text color

ngModel Example

<input

[(ngModel)]="username">

Result

Synchronizes input value

Attribute Directive Architecture

sequenceDiagram

participant Component

participant Directive

participant DOM

Component->>Directive: Property Changed

Directive->>DOM: Update Style/Class

DOM-->>Browser: Repaint

Structural Directives

Structural Directives modify the layout of the DOM by creating, removing, or replacing elements.

Examples:

  • *ngIf
  • *ngFor
  • *ngSwitch

Only one structural directive can be applied directly to the same host element using the * shorthand.


Structural Directive Flow

flowchart TD

Condition

Condition --> True

Condition --> False

True --> CreateDOM

False --> RemoveDOM

ngIf Example

isLoggedIn = true;
<h2

*ngIf="isLoggedIn">

Welcome

</h2>

If

true

Element exists.

If

false

Element is removed from the DOM.


ngFor Example

users = [

"Venu",

"John",

"David"

];
<li

*ngFor="let user of users">

{{user}}

</li>

Result

Creates multiple DOM elements

ngSwitch Example

<div [ngSwitch]="status">

<div *ngSwitchCase="'ACTIVE'">

Active

</div>

<div *ngSwitchDefault>

Unknown

</div>

</div>

Structural Directive Architecture

sequenceDiagram

participant Component

participant StructuralDirective

participant DOM

Component->>StructuralDirective: Condition

StructuralDirective->>DOM: Create or Remove Elements

DOM-->>Browser: Render Updated UI

Attribute vs Structural Directives

flowchart LR

Directive

Directive --> Attribute

Directive --> Structural

Attribute --> ModifyElement

Structural --> ModifyDOM

Comparison Table

Feature Attribute Directive Structural Directive
Purpose Change appearance/behavior Change DOM structure
DOM Creation ❌ No ✅ Yes
DOM Removal ❌ No ✅ Yes
Uses * ❌ No ✅ Yes
Example ngClass *ngIf
Example ngStyle *ngFor
Example ngModel *ngSwitch

How Structural Directives Work

Angular rewrites:

<div *ngIf="isLoggedIn">

Welcome

</div>

Internally into an <ng-template> representation before rendering.

Conceptually:

<ng-template [ngIf]="isLoggedIn">

<div>

Welcome

</div>

</ng-template>

Why Only One Structural Directive?

This is invalid:

<div

*ngIf="loggedIn"

*ngFor="let user of users">

</div>

Reason:

Both directives attempt to transform the same host element.

Correct approach:

<ng-container *ngIf="loggedIn">

<div

*ngFor="let user of users">

{{user}}

</div>

</ng-container>

Angular 17 Control Flow

Angular 17 introduced built-in Control Flow.

Traditional

<div *ngIf="loggedIn">

Welcome

</div>

Modern

@if(loggedIn){

<div>

Welcome

</div>

}

Traditional

<li *ngFor="let user of users">

{{user}}

</li>

Modern

@for(user of users;
track user.id){

<li>

{{user.name}}

</li>

}

Custom Attribute Directive

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {

  constructor(private element: ElementRef) {
    this.element.nativeElement.style.background = 'yellow';
  }

}

Usage

<p appHighlight>

Highlighted Text

</p>

Custom Structural Directive

import {
  Directive,
  Input,
  TemplateRef,
  ViewContainerRef
} from '@angular/core';

@Directive({
  selector: '[appIf]',
  standalone: true
})
export class AppIfDirective {

  constructor(
    private template: TemplateRef<unknown>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input()
  set appIf(condition: boolean) {

    this.viewContainer.clear();

    if (condition) {
      this.viewContainer.createEmbeddedView(this.template);
    }

  }

}

Usage

<div *appIf="isAdmin">

Admin Panel

</div>

Enterprise Banking Dashboard

flowchart TD

Dashboard

Dashboard --> ngIf

Dashboard --> ngFor

Dashboard --> ngClass

Dashboard --> ngStyle

ngIf --> LoginPanel

ngFor --> Accounts

ngClass --> StatusBadge

ngStyle --> BalanceColor

Example

@if(accounts.length){

@for(account of accounts;
track account.id){

<div

[ngClass]="{
  premium: account.vip
}"

[ngStyle]="{
  color: account.balance < 0 ? 'red' : 'green'
}">

{{account.balance | currency}}

</div>

}

}

Performance Considerations

Practice Benefit
Use trackBy or track for lists Reuse DOM elements
Use @if / @for in Angular 17+ Cleaner templates
Avoid deeply nested directives Better readability
Use OnPush when appropriate Better rendering performance
Prefer ng-container Avoid unnecessary wrapper elements

Common Mistakes

Using ngIf Instead of Hidden

Use *ngIf when you want to remove elements from the DOM.

Use [hidden] when you only need to hide an element while keeping it in the DOM.


Multiple Structural Directives

❌ Incorrect

<div

*ngIf="condition"

*ngFor="let user of users">

</div>

Use ng-container or nested elements instead.


Heavy Logic Inside Templates

Avoid

<div *ngIf="calculateSalary(employee)">

</div>

Move complex logic to the component.


Best Practices

  • Use Attribute Directives for styling and behavior.
  • Use Structural Directives for conditional rendering and iteration.
  • Prefer @if and @for in Angular 17+ projects.
  • Use ng-container when combining structural directives.
  • Keep template expressions simple.
  • Use trackBy or track for large lists.
  • Create reusable custom directives for shared behavior.

Advantages

Attribute Directives Structural Directives
Reuse behavior Dynamic UI
Cleaner styling Conditional rendering
Easy customization Efficient DOM management
Lightweight Supports complex layouts
Declarative Reusable templates

Top 10 Angular Attribute vs Structural Directives Interview Questions

1. What is an Angular Directive?

Answer

A Directive is a class that adds behavior to DOM elements. Angular supports Components, Attribute Directives, and Structural Directives.


2. What is an Attribute Directive?

Answer

An Attribute Directive changes the appearance or behavior of an existing element without modifying the DOM structure.

Examples:

  • ngClass
  • ngStyle
  • ngModel

3. What is a Structural Directive?

Answer

A Structural Directive changes the DOM structure by adding, removing, or replacing elements.

Examples:

  • *ngIf
  • *ngFor
  • *ngSwitch

4. What is the main difference between Attribute and Structural Directives?

Attribute Directive Structural Directive
Modifies existing element Modifies DOM structure
Doesn't create/remove elements Creates/removes elements
No * syntax Uses * shorthand

5. Why do Structural Directives use *?

Answer

The * is shorthand that Angular expands into an underlying <ng-template> representation, simplifying template syntax.


6. Why can only one Structural Directive be applied directly to an element?

Answer

Because the * shorthand transforms the host element into a single <ng-template>. Multiple structural transformations on the same element would conflict. Use ng-container or nested elements instead.


7. What are examples of Attribute Directives?

Answer

  • ngClass
  • ngStyle
  • ngModel

8. What are Angular 17 Control Flow directives?

Answer

Angular 17 introduced:

  • @if
  • @for
  • @switch

These provide a cleaner alternative to traditional structural directives.


9. When should you create a Custom Directive?

Answer

Create a Custom Directive when behavior or UI logic needs to be reused across multiple components.


10. What are the best practices for using directives?

Answer

  • Use Attribute Directives for styling and behavior.
  • Use Structural Directives for conditional rendering.
  • Prefer Angular 17 Control Flow for new projects.
  • Use trackBy or track for lists.
  • Keep templates simple.
  • Reuse custom directives for common behavior.

Interview Cheat Sheet

Topic Remember
Appearance Attribute Directive
DOM Structure Structural Directive
ngClass Attribute
ngStyle Attribute
ngModel Attribute
ngIf Structural
ngFor Structural
ngSwitch Structural
Angular 17 @if, @for, @switch
Multiple Structural Directives Use ng-container

Summary

Attribute Directives and Structural Directives serve different purposes in Angular applications. Attribute Directives modify the appearance or behavior of existing DOM elements, while Structural Directives create, remove, or rearrange elements to build dynamic user interfaces. With Angular 17's built-in Control Flow (@if, @for, and @switch), developers can write cleaner, more readable templates while preserving the same core concepts. Understanding when to use each directive type is essential for building scalable, maintainable Angular applications.


Key Takeaways

  • ✔ Attribute Directives modify existing DOM elements.
  • ✔ Structural Directives modify the DOM structure.
  • ngClass, ngStyle, and ngModel are Attribute Directives.
  • *ngIf, *ngFor, and *ngSwitch are Structural Directives.
  • ✔ Angular 17 introduces @if, @for, and @switch.
  • ✔ Only one Structural Directive can use the * shorthand on a host element.
  • ✔ Use ng-container to combine structural directives.
  • ✔ Keep directives reusable and focused.
  • ✔ Use trackBy or track for dynamic lists.
  • ✔ Directives are a core Angular interview topic.

Next Article

➡️ 29-ngClass-ngStyle-QA.md