Angular is a powerful front-end framework that offers building dynamic web applications. One of the most powerful features of Angular is directives. Which allow developers to extend HTML's capabilities and control the Document Object Model (DOM) in custom and reusable ways.
What are directives? What are the types of directives?
Directives are classes that add additional behavior to elements in your Angular applications.
-
Component Directive: The Directive is responsible for showing the first whole view. It is the most used one. Start with the @ sign. Like: @Component.
- Structural Directive: The Directive is responsible for adding and deleting HTML elements in the view. Start with the * sign. Like: *ngIf, *ngFor, *ngSwitch.
- Attribute Directive: The Directive is responsible for changing the appearance of the view by adding or removing style/cssClasses of the html elements.
Creating a Custom Directive
Custom directives empower developers to encapsulate reusable behavior. Let's create an example where a directive highlights text when the user hovers over it.
1. Generate the Directive
you can generate a directive using CLI or also manually add directive
Using CLI:
ng generate directive highlight
2. Add Login for highlight text on hover in highlight.directive.ts
file
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]',
})
export class HighlightDirective {
@Input() highlightColor: string = 'yellow';
constructor(private el: ElementRef) {}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
@HostListener('mouseenter')
onMouseEnter() {
this.highlight(this.highlightColor);
}
@HostListener('mouseleave')
onMouseLeave() {
this.highlight('');
}
}
3. Import the directive into the module in which it is to be component. I am importing in app.module.ts
import {
NgModule,
} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HighlightDirective } from './highlight.directive';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, HighlightDirective],
bootstrap: [AppComponent],
providers: [
],
})
export class AppModule {}
4. Use the directive in a component HTML.
<p appHighlight highlightColor="green">
Hover over the text to see the hightlight effect!
</p>
Output:

Built-in Directives
-
Structural Directives
- *ngIf: Conditionally include an element.
- *ngFor: Loop through a list of items.
- *ngSwitch: Display elements based on conditions.
-
Attribute Directives
- [ngClass]: Add dynamic CSS classes.
- [ngStyle]: Add dynamic inline styles.
Conclusion
Directives in Angular are a powerful tool for manipulating the DOM and building dynamic, reusable components.
If you have any questions or concerns, please feel free to let us know. Our team will connect with you shortly to assist.
Login to leave a comment.