Which of the following best explains why Angular uses directives?
Think about how Angular helps you add behavior to HTML elements.
Directives let you add custom behavior to elements and create reusable UI parts. They help manipulate the DOM in a clean way.
Consider the Angular structural directive *ngIf. What does it do to the DOM?
Think about how *ngIf controls whether something shows or not.
*ngIf adds or removes elements from the DOM depending on the condition you give it, so the element is only present when needed.
Which option shows the correct way to define a custom attribute directive in Angular?
import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) { this.el.nativeElement.style.backgroundColor = 'yellow'; } }
Remember attribute directives use @Directive and selectors with square brackets.
Attribute directives use @Directive with a selector in square brackets to apply behavior to existing elements.
In an Angular directive, which lifecycle hook is best to safely access and manipulate the DOM elements?
Think about when the view and child elements are fully initialized.
ngAfterViewInit runs after Angular fully initializes the component's views and child views, so DOM elements are ready to be accessed.
Given this directive code, why does the element's text color not change to red?
import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appRedText]' }) export class RedTextDirective { constructor(private el: ElementRef) { el.nativeElement.style.color = 'red'; } }
Check if the directive is properly registered in Angular.
If a directive is not declared in an Angular module, Angular does not know about it and will not apply it to elements.