1. What is Directives in Angular?
In Angular, directives are annotations on a DOM element (like an attribute, element name, comment, or CSS class) that instruct Angular’s HTML compiler ($compile
) to apply a particular behavior to that DOM element or modify the DOM element and its children.
Directives in Angular can be generally divided into two categories:
2. Understanding Different types of Angular Directives:
a. Structural Directives:
These modify the DOM layout by inserting or deleting DOM elements.
Here are some examples: *ngIf
, *ngFor
, and *ngSwitch
.
b. Attribute Directives:
These modify how an element, component, or another directive looks or acts.
For instance: ngModel
, ngStyle
, ngClass
.
3. Structural Directives Vs. Attribute Directives:
Structural Directives:
- They manipulate the DOM’s structure.
- They usually have an asterisk (*) prefix.
- They frequently use templates or adjust the layout of the DOM.
- Some examples are
*ngIf
,*ngFor
, and*ngSwitch
.
Attribute Directives:
- They modify how an element, component, or directive looks or acts.
- They typically don’t change the DOM layout.
- Some examples are
ngModel
,ngStyle
, andngClass
.
4. Exploring all the Angular Structural and Attribute Directives:
Structural Directives:
1. ngIf: Displays part of the template only if a specific expression evaluates to true.
<div *ngIf="showElement">Content to show</div>
2. ngFor: Loops through an array of items and displays a template for each one.
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
3.ngSwitch:Switch-case statement for templates.
<div [ngSwitch]="value">
<div *ngSwitchCase="'A'">Case A</div>
<div *ngSwitchCase="'B'">Case B</div>
<div *ngSwitchDefault>Default Case</div>
</div>
Attribute Directives:
1.ngModelLinks the values of HTML controls such as input, select, and textarea to the data within the application.
<input [(ngModel)]="name" />
2.ngStyleSets one or more inline styles dynamically.
<div [ngStyle]="{ 'color': textColor, 'font-size': fontSize }">Styled content</div>
3. ngClass Dynamically applies or removes CSS classes depending on the outcome of an expression.
<div [ngClass]="{ 'active': isActive, 'error': hasError }">Styled content</div>
5. Creating Custom Attribute Directives:
Custom attribute directives enable the creation of reusable behaviors that can be attached to elements within your templates.
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appCustomAttribute]'
})
export class CustomAttributeDirective {
constructor(private elementRef: ElementRef) {
this.elementRef.nativeElement.style.backgroundColor = 'yellow';
}
}
Usage in template:
<div appCustomAttribute>Custom Attribute Directive Example</div>
6. Creating Custom Structural Directives:
"With custom structural directives, you can modify the DOM's structure according to specific conditions."
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appCustomStructural]'
})
export class CustomStructuralDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
@Input() set appCustomStructural(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
Usage in template:
<div *appCustomStructural="isVisible">Custom Structural Directive Example</div>
7. Writing Attribute Directive Code:
Custom attribute directives have the ability to react to alterations on the host element or manage events.
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appCustomAttribute]'
})
export class CustomAttributeDirective {
constructor(private elementRef: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.elementRef.nativeElement.style.backgroundColor = color;
}
}
Usage in template:
<div appCustomAttribute>Hover me to see the effect</div>
8. Respond to User Initiated Events:
Directives can respond to user-initiated events using HostListener.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appCustomEvent]'
})
export class CustomEventDirective {
@HostListener('click', ['$event']) onClick(event: MouseEvent) {
console.log('Element clicked', event);
}
}
Usage in template:
<button appCustomEvent>Click me</button>
9. Pass and Receive Property Values:
Using @Input and @Output decorators allows you to transfer property values.
import { Directive, Input } from '@angular/core';
@Directive({
selector: '[appCustomInput]'
})
export class CustomInputDirective {
@Input() backgroundColor: string;
constructor(private elementRef: ElementRef) {}
ngOnChanges() {
this.elementRef.nativeElement.style.backgroundColor = this.backgroundColor;
}
}
Usage in template:
<div [appCustomInput]="dynamicColor">Change my background color</div>
In this instance, dynamicColor
could be a property within your component that updates as time progresses.
These instances illustrate how to create and utilize custom attribute and structural directives in Angular, as well as how to manage events and transfer property values.