0
0
Angularframework~30 mins

Why directives are needed in Angular - See It in Action

Choose your learning style9 modes available
Why directives are needed in Angular
📖 Scenario: You are building a simple Angular app to display a list of tasks. You want to reuse a piece of HTML code that highlights tasks that are completed. Instead of repeating the same code everywhere, you will create a directive to add this highlight behavior.
🎯 Goal: Build an Angular directive that changes the background color of a task item when it is marked as completed. This shows why directives are needed to add reusable behavior to HTML elements.
📋 What You'll Learn
Create a standalone Angular directive named HighlightCompletedDirective
Use an input property named appHighlightCompleted to receive a boolean indicating if the task is completed
Change the background color of the host element to lightgreen if the task is completed
Keep the background color transparent if the task is not completed
Use the directive in a component template to highlight completed tasks
💡 Why This Matters
🌍 Real World
Directives are used in Angular apps to add custom behavior to elements, such as highlighting, validation, or animations, without repeating code.
💼 Career
Understanding directives is essential for Angular developers to build clean, reusable, and maintainable UI components.
Progress0 / 4 steps
1
Create the Angular directive file
Create a standalone Angular directive named HighlightCompletedDirective with the selector [appHighlightCompleted]. Import Directive and Input from @angular/core.
Angular
Need a hint?

Use @Directive decorator with selector and standalone: true. Add an @Input() property named appHighlightCompleted initialized to false.

2
Add a configuration property for background color
Inside the HighlightCompletedDirective class, create a property named highlightColor and set it to the string 'lightgreen'.
Angular
Need a hint?

Just add a simple property highlightColor with the value 'lightgreen' inside the class.

3
Apply the background color based on the input
Inject ElementRef and Renderer2 in the constructor. Use a setter on appHighlightCompleted to change the host element's background color to highlightColor if true, or to 'transparent' if false.
Angular
Need a hint?

Use ElementRef and Renderer2 to safely change the background color of the host element inside the setter of appHighlightCompleted.

4
Use the directive in a component template
In a component template, use the directive by adding [appHighlightCompleted]="task.completed" on a <li> element inside an *ngFor loop over tasks. Assume tasks is an array of objects with name and completed boolean properties.
Angular
Need a hint?

Use *ngFor="let task of tasks" to loop and add [appHighlightCompleted]="task.completed" on the <li> elements.