Directives let you change how the page looks or behaves by working directly with the page elements. They help you add or change things on the page easily.
Directive execution and DOM manipulation in Angular
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('mouseenter') onMouseEnter() { this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow'); } @HostListener('mouseleave') onMouseLeave() { this.renderer.removeStyle(this.el.nativeElement, 'background-color'); } }
Use @Directive to define a directive and set its selector.
Use ElementRef to access the element and Renderer2 to safely change its style or content.
import { Directive, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: '[appBold]' }) export class BoldDirective { constructor(el: ElementRef, renderer: Renderer2) { renderer.setStyle(el.nativeElement, 'font-weight', 'bold'); } }
import { Directive, HostListener, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: '[appToggle]' }) export class ToggleDirective { private isOn = false; constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('click') toggle() { this.isOn = !this.isOn; const color = this.isOn ? 'green' : 'red'; this.renderer.setStyle(this.el.nativeElement, 'color', color); } }
This example shows a directive that highlights the background of a heading when you move the mouse over it and removes the highlight when the mouse leaves.
import { Component } from '@angular/core'; import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('mouseenter') onMouseEnter() { this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow'); } @HostListener('mouseleave') onMouseLeave() { this.renderer.removeStyle(this.el.nativeElement, 'background-color'); } } @Component({ selector: 'app-root', standalone: true, imports: [HighlightDirective], template: `<h2 appHighlight>Hover over me to see highlight</h2>` }) export class AppComponent {}
Always use Renderer2 for DOM changes to keep your app safe and compatible with different platforms.
Use @HostListener to listen to events like clicks or mouse movements on the element.
Directives should be simple and focused on one task for easier reuse and testing.
Directives let you add or change behavior on HTML elements.
Use ElementRef and Renderer2 to safely manipulate the DOM.
Listen to user events with @HostListener to react to actions like clicks or hovers.
Practice
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 BQuick Check:
Directive purpose = Add/change behavior [OK]
- Confusing directives with modules
- Thinking directives manage routing
- Assuming directives handle HTTP
Renderer2 in a directive's constructor?Solution
Step 1: Recall Angular dependency injection syntax
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 DQuick Check:
Correct DI syntax = private name: Type [OK]
- Swapping parameter order
- Omitting colon between name and type
- Placing access modifier after type
import { Directive, HostListener, Renderer2, ElementRef } from '@angular/core';
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('click') onClick() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
}Solution
Step 1: Understand @HostListener usage
The @HostListener('click') decorator listens for click events on the host element and triggers the onClick method.Step 2: Analyze onClick method
Inside onClick, Renderer2 sets the backgroundColor style of the element to 'yellow'. This changes the element's background color on click.Final Answer:
The element's background color changes to yellow on click -> Option CQuick Check:
@HostListener + Renderer2 changes background [OK]
- Confusing backgroundColor with text color
- Assuming no effect without manual event binding
- Thinking Renderer2 usage causes error
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({ selector: '[appColor]' })
export class ColorDirective {
constructor(el: ElementRef, renderer: Renderer2) {
renderer.setStyle(el.nativeElement, 'color', 'blue');
}
}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 AQuick Check:
DI needs access modifiers in constructor [OK]
- Thinking Renderer2 can't set styles
- Believing selector syntax is wrong
- Assuming ElementRef is disallowed
active on the host element when the user hovers over it, and removes it when the mouse leaves. Which approach correctly implements this behavior?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 AQuick Check:
Hover needs mouseenter/mouseleave + Renderer2 [OK]
- Using click event instead of hover events
- Manipulating DOM directly without Renderer2
- Relying only on @HostBinding without events
Ready to prove it?
Pass the test and this pattern moves unknown
