0
0
Angularframework~30 mins

Directive execution and DOM manipulation in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Directive execution and DOM manipulation
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use the directive as an attribute on the HTML element you want to highlight.