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
Creating a Custom Structural Directive in Angular
📖 Scenario: You are building a simple Angular app that shows a list of tasks. You want to create a custom structural directive that only displays tasks marked as important.
🎯 Goal: Build a custom structural directive called appShowImportant that shows only tasks with important: true in the list.
📋 What You'll Learn
Create an array of tasks with exact objects
Add a boolean config variable to control filtering
Use the custom structural directive to filter tasks
Apply the directive in the template to show only important tasks
💡 Why This Matters
🌍 Real World
Custom structural directives help you create reusable, flexible UI behaviors in Angular apps, such as showing or hiding elements based on complex conditions.
💼 Career
Understanding how to build custom directives is important for Angular developers to extend the framework's capabilities and create clean, maintainable code.
Progress0 / 4 steps
1
Set up the tasks array
Create an array called tasks with these exact objects: { title: 'Buy groceries', important: true }, { title: 'Walk the dog', important: false }, and { title: 'Read a book', important: true }.
Angular
Hint
Use a variable named tasks and assign an array with the exact objects.
2
Add a filter flag
Create a boolean variable called showImportantOnly and set it to true.
Angular
Hint
Just add a boolean variable named showImportantOnly and set it to true.
3
Create the custom structural directive
Create a directive class called ShowImportantDirective with selector [appShowImportant]. Inject TemplateRef and ViewContainerRef in the constructor. Add an input property appShowImportant of type boolean. In the setter of appShowImportant, clear the container and create the embedded view only if the value is true.
Angular
Hint
Use Angular's @Directive decorator and inject TemplateRef and ViewContainerRef. Use an input setter to control view creation.
4
Use the directive in the template
In the template, use *appShowImportant="!showImportantOnly || task.important" on an <li> element inside an <ul> that iterates over tasks with *ngFor="let task of tasks".
Angular
Hint
Use *ngFor to loop over tasks and apply *appShowImportant with the condition !showImportantOnly || task.important.
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
Step 1: Understand structural directives role
Structural directives change the structure of the DOM by adding or removing elements.
Step 2: Identify the main use case
Custom structural directives let you control when parts of the page appear or disappear dynamically.
Final Answer:
To add or remove HTML elements dynamically based on conditions -> Option D
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
Step 1: Identify dependencies for structural directives
Structural directives need TemplateRef to access the template and ViewContainerRef to insert or remove views.
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.
Final Answer:
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {} -> Option C
Step 1: Analyze the directive behavior when condition is false
When appShowIf is false, viewContainer.clear() removes any embedded views, so nothing is rendered.
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.
Final Answer:
Nothing will be rendered inside the div -> Option A
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
Step 1: Check constructor dependencies
The directive injects only TemplateRef but misses ViewContainerRef, which is needed to insert or clear views.
Step 2: Analyze method usage
Calling createEmbeddedView() on TemplateRef alone is invalid; it should be called on ViewContainerRef with TemplateRef as argument.
Final Answer:
Missing ViewContainerRef injection and usage to insert the view -> Option B
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
Step 1: Understand the directive goal
*appUnless should show content only when the condition is false, so the view is created when !condition.
Step 2: Match logic to code
Using if (!condition) to create the embedded view and clearing it otherwise matches the requirement.
Final Answer:
Use if (!condition) to create the embedded view, else clear it -> Option A
Quick Check:
Show content when false = if (!condition) create view [OK]
Hint: Invert condition logic to show content only when false [OK]