Bird
0
0

Which approach correctly implements this behavior?

hard📝 Application Q15 of 15
Angular - Directives
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?
AUse two @HostListener methods for 'mouseenter' and 'mouseleave' to add and remove the class using Renderer2
BUse a single @HostListener for 'click' to toggle the class
CDirectly modify the element's classList without Renderer2 inside the constructor
DUse @HostBinding to bind a boolean and toggle it manually without event listeners
Step-by-Step Solution
Solution:
  1. Step 1: Understand event requirements

    Hover behavior requires reacting to 'mouseenter' and 'mouseleave' events to add and remove the class.
  2. 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.
  3. Final Answer:

    Use two @HostListener methods for 'mouseenter' and 'mouseleave' to add and remove the class using Renderer2 -> Option A
  4. Quick Check:

    Hover needs mouseenter/mouseleave + Renderer2 [OK]
Quick Trick: Use separate HostListeners for mouseenter and mouseleave [OK]
Common Mistakes:
  • Using click event instead of hover events
  • Manipulating DOM directly without Renderer2
  • Relying only on @HostBinding without events

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes