Bird
Raised Fist0
Angularframework~20 mins

Directive execution and DOM manipulation in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Directive Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What will be the rendered output of this Angular directive?

Consider this Angular standalone directive that changes the background color of the host element:

import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
  }
}

If this directive is applied to a <div> with text 'Hello', what will the user see?

Angular
<div appHighlight>Hello</div>
AThe text color will change to yellow but background remains default
BThe text 'Hello' will be bold but no background color change
CThe div will be hidden and not visible on the page
DA yellow background behind the text 'Hello' inside the div
Attempts:
2 left
💡 Hint

Think about what renderer.setStyle does to the host element's style.

❓ lifecycle
intermediate
1:30remaining
When is the best lifecycle hook to safely manipulate the DOM in an Angular directive?

You want to add a CSS class to the host element after it is fully initialized. Which lifecycle hook should you use inside your directive?

Aconstructor
BngOnInit
CngAfterViewInit
DngOnDestroy
Attempts:
2 left
💡 Hint

Consider when the view and child elements are fully rendered.

📝 Syntax
advanced
2:30remaining
Which directive code snippet correctly toggles a CSS class on click?

Choose the correct Angular directive code that toggles the CSS class 'active' on the host element when it is clicked.

A
import { Directive, HostListener, Renderer2, ElementRef } from '@angular/core';

@Directive({ selector: '[appToggle]' })
export class ToggleDirective {
  private active = false;
  constructor(private el: ElementRef, private renderer: Renderer2) {}
  @HostListener('click') toggle() {
    this.active = !this.active;
    if (this.active) {
      this.renderer.addClass(this.el.nativeElement, 'active');
    } else {
      this.renderer.removeClass(this.el.nativeElement, 'active');
    }
  }
}
B
import { Directive, HostListener, Renderer2, ElementRef } from '@angular/core';

@Directive({ selector: '[appToggle]' })
export class ToggleDirective {
  private active = false;
  constructor(private el: ElementRef, private renderer: Renderer2) {}
  @HostListener('click') toggle() {
    this.active = !this.active;
    this.el.nativeElement.classList.toggle('active');
  }
}
C
import { Directive, HostListener, Renderer2, ElementRef } from '@angular/core';

@Directive({ selector: '[appToggle]' })
export class ToggleDirective {
  private active = false;
  constructor(private el: ElementRef, private renderer: Renderer2) {}
  @HostListener('click') toggle() {
    this.active = !this.active;
    this.renderer.setStyle(this.el.nativeElement, 'class', this.active ? 'active' : '');
  }
}
D
import { Directive, HostListener, Renderer2, ElementRef } from '@angular/core';

@Directive({ selector: '[appToggle]' })
export class ToggleDirective {
  private active = false;
  constructor(private el: ElementRef, private renderer: Renderer2) {}
  @HostListener('click') toggle() {
    this.active = !this.active;
    this.renderer.setAttribute(this.el.nativeElement, 'class', this.active ? 'active' : '');
  }
}
Attempts:
2 left
💡 Hint

Remember that renderer.setStyle does not set classes, and direct DOM manipulation is discouraged.

🔧 Debug
advanced
2:00remaining
What error will this Angular directive code cause?

Analyze this directive code snippet:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({ selector: '[appError]' })
export class ErrorDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'blue');
  }

  @HostListener('click') onClick() {
    this.renderer.setStyle(this.el.nativeElement, 'color', 'white');
  }
}

What error will Angular throw when this directive is used?

ASyntaxError due to missing semicolons
BNo error; the directive works as expected
CRuntime error: HostListener decorator missing import
DRuntime error: Cannot read property 'setStyle' of undefined
Attempts:
2 left
💡 Hint

Check if all necessary imports and syntax are correct.

🧠 Conceptual
expert
3:00remaining
Which statement best describes Angular directive execution order and DOM manipulation?

Consider multiple directives applied to the same element. Which statement about their execution and DOM manipulation order is true?

AAll directives execute their constructors first, then lifecycle hooks run in the order of declaration, allowing safe DOM manipulation in ngAfterViewInit
BDirectives execute in the order they appear in the template, and each can manipulate the DOM immediately during construction
CDirectives execute lifecycle hooks in parallel, so DOM manipulation order is unpredictable
DDirectives cannot manipulate the DOM; only components can
Attempts:
2 left
💡 Hint

Think about Angular's lifecycle and when DOM is ready for manipulation.

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

  1. 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.
  2. 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.
  3. Final Answer:

    To add or change behavior on HTML elements -> Option B
  4. 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?
easy
A. constructor(renderer: Renderer2 private) {}
B. constructor(Renderer2 private renderer) {}
C. constructor(private Renderer2 renderer) {}
D. constructor(private renderer: Renderer2) {}

Solution

  1. 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.
  2. Step 2: Match correct syntax

    constructor(private renderer: Renderer2) {} follows the pattern: 'constructor(private renderer: Renderer2) {}'. Other options have incorrect order or missing colons.
  3. Final Answer:

    constructor(private renderer: Renderer2) {} -> Option D
  4. 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?
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');
  }
}
medium
A. The element's text color changes to yellow on click
B. Nothing happens on click
C. The element's background color changes to yellow on click
D. An error occurs because Renderer2 is not used correctly

Solution

  1. Step 1: Understand @HostListener usage

    The @HostListener('click') decorator listens for click events on the host element and triggers the onClick method.
  2. 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.
  3. Final Answer:

    The element's background color changes to yellow on click -> Option C
  4. Quick Check:

    @HostListener + Renderer2 changes background [OK]
Hint: HostListener triggers method; Renderer2 safely changes style [OK]
Common Mistakes:
  • Confusing backgroundColor with text color
  • Assuming no effect without manual event binding
  • Thinking Renderer2 usage causes error
4. Identify the error in this directive code snippet:
import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({ selector: '[appColor]' })
export class ColorDirective {
  constructor(el: ElementRef, renderer: Renderer2) {
    renderer.setStyle(el.nativeElement, 'color', 'blue');
  }
}
medium
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

  1. 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.
  2. Step 2: Identify missing access modifiers

    Here, 'el' and 'renderer' lack 'private' or 'public', so Angular won't inject them properly, causing runtime errors.
  3. Final Answer:

    Missing access modifiers in constructor parameters prevent DI -> Option A
  4. 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

  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]
Hint: 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard