Difference Between Structural and Attribute Directives
๐ก Concept Name
Structural vs Attribute Directives โ Two primary types of Angular directives that change the layout or appearance of elements.
๐ Quick Intro
Angular provides directives to modify the DOM. Structural directives change the structure of the DOM (add/remove elements), while attribute directives change the appearance or behavior of existing elements.
๐ง Analogy / Short Story
Imagine building a Lego house: structural directives are like deciding which bricks to use or remove (affecting structure), while attribute directives are like painting or decorating the house (changing appearance without affecting structure).
๐ง Technical Explanation
- ๐๏ธ Structural Directives: Modify the DOM layout by adding or removing elements. Examples:
*ngIf
,*ngFor
,*ngSwitch
. - ๐จ Attribute Directives: Change the appearance or behavior of an element. Examples:
ngClass
,ngStyle
, custom directives likeappHighlight
. - โ ๏ธ Structural directives are prefixed with
*
, while attribute directives are not.
๐ฏ Purpose & Use Case
- โ Use structural directives for conditional rendering, loops, or switching views.
- โ Use attribute directives to apply styles, CSS classes, or behaviors dynamically.
๐ป Real Code Example
<!-- Structural Directive -->
<div *ngIf="isLoggedIn">Welcome, user!</div>
<!-- Attribute Directive -->
<div [ngStyle]="{color: 'blue'}">This text is blue.</div>
Key Highlight: *ngIf
adds/removes the element; ngStyle
applies a style without changing structure.

โ Interview Q&A
Q1: What is a structural directive?
A: It changes the DOM structure by adding or removing elements.
Q2: What is an attribute directive?
A: It changes the appearance or behavior of an element without altering the DOM structure.
Q3: Name three structural directives in Angular.
A: *ngIf, *ngFor, *ngSwitch.
Q4: Name some attribute directives in Angular.
A: ngClass, ngStyle, custom directives like appHighlight.
Q5: Why is there an asterisk (*) before structural directives?
A: It tells Angular to transform the HTML using TemplateRef
behind the scenes.
๐ MCQs
Q1. Which directive modifies the structure of the DOM?
- [ngClass]
- *ngIf
- (click)
- [ngStyle]
Q2. Which directive changes only the appearance or behavior?
- *ngFor
- [ngStyle]
- *ngIf
- *ngSwitch
Q3. What does the asterisk (*) signify in a directive like *ngIf?
- Attribute directive
- Style binding
- Structural directive
- Event binding
Q4. Which directive is used to add CSS classes dynamically?
- *ngIf
- [ngClass]
- [style]
- *ngSwitch
Q5. Can attribute directives remove DOM elements?
- Yes
- No
- Sometimes
- Only with * prefix
๐ก Bonus Insight
You can create your own custom structural or attribute directives in Angular using the @Directive
decorator and by injecting ElementRef
and Renderer2
for manipulation.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!