Complete the code to create a standalone Angular directive that changes the background color of an element.
import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]', standalone: true }) export class HighlightDirective { constructor(private el: ElementRef) { this.el.nativeElement.style.backgroundColor = [1]; } }
The backgroundColor style property expects a string value representing the color. So, it must be wrapped in quotes like 'yellow'.
Complete the code to listen for click events inside a directive and log a message.
import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[appClickLogger]', standalone: true }) export class ClickLoggerDirective { @HostListener('click') onClick() { console.log([1]); } }
The console.log expects a string message, so it must be wrapped in quotes.
Fix the error in the directive that tries to add a CSS class to the host element.
import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appAddClass]', standalone: true }) export class AddClassDirective { constructor(private el: ElementRef) { this.el.nativeElement.classList.[1]('active'); } }
The correct method to add a CSS class to an element's classList is 'add'.
Fill both blanks to create a directive that toggles a CSS class on click.
import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appToggleClass]', standalone: true }) export class ToggleClassDirective { private isActive = false; constructor(private el: ElementRef) {} @HostListener('click') onClick() { this.isActive = !this.isActive; this.el.nativeElement.classList.[1]('active'); if (!this.isActive) { this.el.nativeElement.classList.[2]('active'); } } }
When toggling manually, use 'add' to add the class and 'remove' to remove it based on the state.
Fill all three blanks to create a directive that changes text content on mouse enter and leave.
import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appHoverText]', standalone: true }) export class HoverTextDirective { private originalText = ''; constructor(private el: ElementRef) { this.originalText = this.el.nativeElement.[1]; } @HostListener('mouseenter') onMouseEnter() { this.el.nativeElement.[2] = [3]; } @HostListener('mouseleave') onMouseLeave() { this.el.nativeElement.textContent = this.originalText; } }
The original text is stored from 'textContent'. On mouse enter, 'innerText' is changed to the string 'Hovered!'.