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?
<div appHighlight>Hello</div>
Think about what renderer.setStyle does to the host element's style.
The directive uses Renderer2 to set the background-color style of the host element to yellow. This means the div's background will appear yellow behind the text.
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?
Consider when the view and child elements are fully rendered.
ngAfterViewInit runs after Angular has fully initialized the component's view and child views, making it safe to manipulate the DOM.
Choose the correct Angular directive code that toggles the CSS class 'active' on the host element when it is clicked.
Remember that renderer.setStyle does not set classes, and direct DOM manipulation is discouraged.
Option A uses renderer.addClass and renderer.removeClass properly to toggle the class. Option A tries to set style 'class' which is invalid. Option A manipulates DOM directly which is discouraged. Option A sets attribute 'class' which overwrites all classes.
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?
Check if all necessary imports and syntax are correct.
The code imports all needed symbols, uses Renderer2 correctly, and the missing semicolons do not cause errors in TypeScript. The HostListener decorator is now shown imported. If imported, no runtime error occurs.
Consider multiple directives applied to the same element. Which statement about their execution and DOM manipulation order is true?
Think about Angular's lifecycle and when DOM is ready for manipulation.
Angular calls constructors of all directives first, then lifecycle hooks like ngOnInit and ngAfterViewInit in declaration order. DOM manipulation should happen in ngAfterViewInit to ensure the view is ready.