0
0
Angularframework~30 mins

Custom structural directives in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use *ngFor to loop over tasks and apply *appShowImportant with the condition !showImportantOnly || task.important.