Complete the code to create a simple Angular directive that changes text color.
import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) { this.el.nativeElement.style.color = [1]; } }
The directive changes the text color by setting the style.color property. The correct value is a color string like 'blue'.
Complete the code to apply the directive to a paragraph element in the template.
<p [1]>This text will be highlighted.</p>The directive selector is '[appHighlight]', so to apply it, use the attribute appHighlight on the element.
Fix the error in the directive code to properly inject ElementRef.
import { Directive, [1] } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) {} }
The ElementRef class must be imported to inject it in the constructor for DOM access.
Fill both blanks to create a directive that changes background color on mouse enter and resets on mouse leave.
import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appHover]' }) export class HoverDirective { constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.el.nativeElement.style.backgroundColor = [1]; } @HostListener('mouseleave') onMouseLeave() { this.el.nativeElement.style.backgroundColor = [2]; } }
On mouse enter, the background color changes to 'yellow'. On mouse leave, it resets to 'transparent' to remove the highlight.
Fill all three blanks to create a structural directive that shows content only if a condition is true.
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core'; @Directive({ selector: '[appIf]' }) export class IfDirective { constructor(private [1]: TemplateRef<any>, private [2]: ViewContainerRef) {} @Input() set appIf(condition: boolean) { if (condition) { this.[3].createEmbeddedView(this.templateRef); } else { this.viewContainer.clear(); } } }
The constructor injects templateRef and viewContainer. The viewContainer creates or clears the embedded view based on the condition.