📖 Scenario: You are building a simple Angular app that highlights text when a user hovers over it. This helps users focus on important parts of the page.
🎯 Goal: Create a custom Angular directive that changes the background color of a text element when the mouse is over it and resets it when the mouse leaves.
📋 What You'll Learn
Create a standalone Angular directive named HighlightDirective.
Use Angular's ElementRef and Renderer2 to manipulate the DOM safely.
Add event listeners for mouseenter and mouseleave to change and reset the background color.
Use the color yellow for highlighting.
💡 Why This Matters
🌍 Real World
Custom directives are used in Angular apps to add reusable behavior to elements, such as highlighting, tooltips, or animations.
💼 Career
Understanding directive creation and DOM manipulation is essential for Angular developers to build interactive and accessible user interfaces.
Progress0 / 4 steps
1
Create the directive class with constructor
Create a standalone Angular directive named HighlightDirective. Import Directive, ElementRef, and Renderer2 from @angular/core. Inside the directive class, create a constructor that injects private el: ElementRef and private renderer: Renderer2.
Angular
Hint
Remember to import all required Angular core symbols and use the @Directive decorator with standalone: true.
2
Add event listeners for mouseenter and mouseleave
Inside the HighlightDirective constructor, add event listeners for mouseenter and mouseleave on this.el.nativeElement. For now, leave the event handler functions empty.
Angular
Hint
Use this.el.nativeElement.addEventListener to listen for mouse events.
3
Change background color on mouseenter and reset on mouseleave
Inside the mouseenter event listener, use this.renderer.setStyle to set the background color of this.el.nativeElement to 'yellow'. Inside the mouseleave event listener, reset the background color to '' (empty string) using this.renderer.setStyle.
Angular
Hint
Use this.renderer.setStyle(element, 'backgroundColor', color) to change styles safely.
4
Use the directive in a component template
In an Angular component template, add a <p> element with the text 'Hover over me!' and apply the appHighlight directive as an attribute to it.
Angular
Hint
Use the directive as an attribute on the HTML element you want to highlight.
Practice
(1/5)
1. What is the primary purpose of an Angular directive?
easy
A. To create new Angular modules
B. To add or change behavior on HTML elements
C. To define routes in the application
D. To manage HTTP requests
Solution
Step 1: Understand what directives do
Directives in Angular are used to add or change behavior on HTML elements, such as changing styles or responding to events.
Step 2: Compare with other Angular features
Modules organize code, routes manage navigation, and HTTP requests handle data fetching, which are not the main roles of directives.
Final Answer:
To add or change behavior on HTML elements -> Option B
Quick Check:
Directive purpose = Add/change behavior [OK]
Hint: Directives change element behavior, not app structure [OK]
Common Mistakes:
Confusing directives with modules
Thinking directives manage routing
Assuming directives handle HTTP
2. Which syntax correctly injects Renderer2 in a directive's constructor?
Angular uses TypeScript constructor parameters with access modifiers like 'private' before the variable name and type after the colon.
Step 2: Match correct syntax
constructor(private renderer: Renderer2) {} follows the pattern: 'constructor(private renderer: Renderer2) {}'. Other options have incorrect order or missing colons.
Final Answer:
constructor(private renderer: Renderer2) {} -> Option D
Quick Check:
Correct DI syntax = private name: Type [OK]
Hint: Use 'private name: Type' in constructor for DI [OK]
Common Mistakes:
Swapping parameter order
Omitting colon between name and type
Placing access modifier after type
3. Given this directive code, what will happen when the user clicks the host element?
A. Missing access modifiers in constructor parameters prevent DI
B. Renderer2 cannot set styles directly
C. Selector syntax is invalid
D. ElementRef should not be used in directives
Solution
Step 1: Check constructor parameters for DI
Angular dependency injection requires constructor parameters to have access modifiers like 'private' or 'public' to assign them as class properties.
Step 2: Identify missing access modifiers
Here, 'el' and 'renderer' lack 'private' or 'public', so Angular won't inject them properly, causing runtime errors.
Final Answer:
Missing access modifiers in constructor parameters prevent DI -> Option A
Quick Check:
DI needs access modifiers in constructor [OK]
Hint: Always add 'private' or 'public' for DI in constructor [OK]
Common Mistakes:
Thinking Renderer2 can't set styles
Believing selector syntax is wrong
Assuming ElementRef is disallowed
5. You want to create a directive that toggles a CSS class active on the host element when the user hovers over it, and removes it when the mouse leaves. Which approach correctly implements this behavior?
hard
A. Use two @HostListener methods for 'mouseenter' and 'mouseleave' to add and remove the class using Renderer2
B. Use a single @HostListener for 'click' to toggle the class
C. Directly modify the element's classList without Renderer2 inside the constructor
D. Use @HostBinding to bind a boolean and toggle it manually without event listeners
Solution
Step 1: Understand event requirements
Hover behavior requires reacting to 'mouseenter' and 'mouseleave' events to add and remove the class.
Step 2: Use Renderer2 with @HostListener
Using two @HostListener methods for these events and Renderer2 to add/remove the 'active' class is the safe and correct Angular way.
Final Answer:
Use two @HostListener methods for 'mouseenter' and 'mouseleave' to add and remove the class using Renderer2 -> Option A