Q1. What are directives in Angular?
Directives are classes that add behavior to elements in Angular applications. There are three types: components (directives with templates), structural directives (change DOM layout by adding/removing elements, e.g., *ngIf, *ngFor), and attribute directives (change appearance or behavior, e.g., ngClass, ngStyle). Directives use the @Directive decorator.
Q2. What is the difference between component and directive?
A component is a directive with a template. Components are the main building blocks for UI. Directives without templates modify elements or add behavior. For example, a component renders its own view, while an attribute directive like ngStyle changes the style of an existing element.
Q3. What are structural directives?
Structural directives shape or reshape the DOM''s structure by adding, removing, or manipulating elements. They are prefixed with an asterisk (*), e.g., *ngIf, *ngFor, *ngSwitch. They can only be used on host elements. Angular translates the asterisk into around the element.
Q4. What are attribute directives?
Attribute directives change the appearance or behavior of an element, component, or another directive. They are used as element attributes, e.g., ngClass, ngStyle, or custom directives. They don''t change the DOM structure but modify the element they''re attached to.
Q5. How do you create a custom directive?
Use the @Directive decorator and implement the desired behavior. Example custom attribute directive that changes background color:
@Directive({
selector: ''[appHighlight]''
})
export class HighlightDirective {
@Input() appHighlight = '''';
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = ''yellow'';
}
}
