Bird
Raised Fist0
Angularframework~10 mins

Custom structural directives in Angular - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Custom structural directives
Start: Angular template
Detect *directive syntax
Call directive's constructor
Directive receives TemplateRef & ViewContainerRef
Directive decides when/how to add/remove views
ViewContainerRef creates embedded views
Angular renders embedded views in DOM
Directive updates views on input changes
End: DOM reflects directive logic
Angular reads the template, finds the custom structural directive, then uses its logic to add or remove parts of the DOM dynamically.
Execution Sample
Angular
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[appShow]' })
export class ShowDirective {
  constructor(private tpl: TemplateRef<any>, private vcr: ViewContainerRef) {}

  @Input() set appShow(condition: boolean) {
    this.vcr.clear();
    if (condition) this.vcr.createEmbeddedView(this.tpl);
  }
}
This directive shows or hides a template part based on a boolean input.
Execution Table
StepActionInput ConditionViewContainerRef StateDOM Change
1Directive instantiatedN/AEmptyNo DOM added
2Input appShow set to truetrueCleared then view createdTemplate inserted in DOM
3Input appShow set to falsefalseClearedTemplate removed from DOM
4Input appShow set to true againtrueCleared then view createdTemplate re-inserted in DOM
5No further input changesN/AView remainsDOM unchanged
6End of traceN/AFinal state keptDOM reflects last input
💡 Execution stops as no more input changes occur; DOM matches directive logic.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
conditionundefinedtruefalsetruetrue
ViewContainerRef stateemptyview createdclearedview createdview created
Key Moments - 3 Insights
Why does the directive clear the ViewContainerRef before creating a new view?
Clearing removes any previously rendered views to avoid duplicates. See execution_table rows 2 and 3 where clearing happens before creating or removing views.
What happens if the input condition is false?
The directive clears the container and does not create a view, so the template is removed from the DOM. See execution_table row 3.
How does Angular know where to insert the template in the DOM?
Angular uses the ViewContainerRef linked to the directive's host element to insert or remove embedded views dynamically.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the ViewContainerRef state after step 3?
AView created
BUnchanged
CCleared
DError state
💡 Hint
Check the 'ViewContainerRef State' column in row 3 of the execution_table.
At which step does the template get inserted back into the DOM after being removed?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look for when the input condition changes back to true and a view is created again.
If the input condition never changes from true, how would the execution_table change?
ANo clearing steps would occur
BViews would be created and cleared repeatedly
CThe template would never be inserted
DThe directive would throw an error
💡 Hint
Refer to variable_tracker for condition changes and execution_table for clearing actions.
Concept Snapshot
Custom structural directives in Angular
- Use @Directive with selector like '[appShow]'
- Inject TemplateRef and ViewContainerRef
- Control DOM by creating/removing embedded views
- Use input setters to react to changes
- Clear container before adding views to avoid duplicates
Full Transcript
Custom structural directives in Angular let you add or remove parts of the page dynamically. Angular reads the template and finds your directive marked with a star (*). It calls your directive's constructor, giving you the template and a place to insert views. Your directive decides when to add or remove these views based on input values. For example, if the input is true, it creates the view and inserts it into the DOM. If false, it clears the container, removing the view. This process repeats whenever the input changes, keeping the page in sync with your logic.

Practice

(1/5)
1. What is the main purpose of a custom structural directive in Angular?
easy
A. To style elements with CSS classes
B. To fetch data from a server
C. To handle user input events
D. To add or remove HTML elements dynamically based on conditions

Solution

  1. Step 1: Understand structural directives role

    Structural directives change the structure of the DOM by adding or removing elements.
  2. Step 2: Identify the main use case

    Custom structural directives let you control when parts of the page appear or disappear dynamically.
  3. Final Answer:

    To add or remove HTML elements dynamically based on conditions -> Option D
  4. Quick Check:

    Structural directives = dynamic HTML blocks [OK]
Hint: Structural directives control HTML blocks, not styles or events [OK]
Common Mistakes:
  • Confusing structural directives with attribute directives
  • Thinking they handle styling or events
  • Assuming they fetch data
2. Which of the following is the correct way to inject dependencies in a custom structural directive constructor?
easy
A. constructor(private http: HttpClient) {}
B. constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
C. constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
D. constructor(private router: Router) {}

Solution

  1. Step 1: Identify dependencies for structural directives

    Structural directives need TemplateRef to access the template and ViewContainerRef to insert or remove views.
  2. Step 2: Match constructor parameters

    constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {} correctly injects TemplateRef and ViewContainerRef, which are essential for custom structural directives.
  3. Final Answer:

    constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {} -> Option C
  4. Quick Check:

    TemplateRef + ViewContainerRef = constructor params [OK]
Hint: Use TemplateRef and ViewContainerRef in constructor for structural directives [OK]
Common Mistakes:
  • Injecting ElementRef or Renderer2 which are for attribute directives
  • Injecting unrelated services like HttpClient or Router
  • Missing TemplateRef or ViewContainerRef
3. Given this directive code snippet, what will be the rendered output if appShowIf input is false?
@Directive({ selector: '[appShowIf]' })
export class ShowIfDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
  @Input() set appShowIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}

Usage:
<div *appShowIf="false">Hello World</div>
medium
A. Nothing will be rendered inside the div
B. The text 'Hello World' will be displayed
C. An error will occur because of wrong syntax
D. The div will be rendered but empty

Solution

  1. Step 1: Analyze the directive behavior when condition is false

    When appShowIf is false, viewContainer.clear() removes any embedded views, so nothing is rendered.
  2. Step 2: Understand the usage effect

    The <div> with 'Hello World' is inside the template controlled by the directive, so it won't appear if condition is false.
  3. Final Answer:

    Nothing will be rendered inside the div -> Option A
  4. Quick Check:

    False condition = no content shown [OK]
Hint: False input clears view container, so no content appears [OK]
Common Mistakes:
  • Thinking the div still renders empty
  • Assuming an error occurs
  • Confusing attribute directives with structural directives
4. Identify the error in this custom structural directive code:
@Directive({ selector: '[appIf]' })
export class IfDirective {
  constructor(private templateRef: TemplateRef<any>) {}
  @Input() set appIf(condition: boolean) {
    if (condition) {
      this.templateRef.createEmbeddedView();
    }
  }
}
medium
A. Incorrect selector syntax in @Directive decorator
B. Missing ViewContainerRef injection and usage to insert the view
C. Wrong input property name, should be 'appIfCondition'
D. No error, code is correct

Solution

  1. Step 1: Check constructor dependencies

    The directive injects only TemplateRef but misses ViewContainerRef, which is needed to insert or clear views.
  2. Step 2: Analyze method usage

    Calling createEmbeddedView() on TemplateRef alone is invalid; it should be called on ViewContainerRef with TemplateRef as argument.
  3. Final Answer:

    Missing ViewContainerRef injection and usage to insert the view -> Option B
  4. Quick Check:

    ViewContainerRef required to add views [OK]
Hint: Always inject ViewContainerRef to add or remove views [OK]
Common Mistakes:
  • Trying to create views directly from TemplateRef
  • Forgetting to inject ViewContainerRef
  • Misnaming input properties
5. You want to create a custom structural directive *appUnless that shows content only when a condition is false. Which implementation correctly achieves this behavior?
hard
A. Use if (!condition) to create the embedded view, else clear it
B. Use if (condition) to create the embedded view, else clear it
C. Always create the embedded view regardless of condition
D. Clear the view only when condition is false

Solution

  1. Step 1: Understand the directive goal

    *appUnless should show content only when the condition is false, so the view is created when !condition.
  2. Step 2: Match logic to code

    Using if (!condition) to create the embedded view and clearing it otherwise matches the requirement.
  3. Final Answer:

    Use if (!condition) to create the embedded view, else clear it -> Option A
  4. Quick Check:

    Show content when false = if (!condition) create view [OK]
Hint: Invert condition logic to show content only when false [OK]
Common Mistakes:
  • Using if (condition) instead of if (!condition)
  • Not clearing the view when condition is true
  • Creating view unconditionally