Angular is a powerful, a robust JavaScript framework that enables developers to build dynamic and interactive web applications. As I delved into my Angular learning journey, I discovered an interesting subject, which is the ability to create custom directives, which allow us to extend HTML functionality and create reusable components and behaviors. In this blog, we will explore the concept of custom Angular directives and learn how to create our own.
What are Angular Directives?
Angular directives are markers on DOM elements that instruct the HTML compiler to attach specific behaviors and transform those elements. They are essentially functions that get executed when the compiler encounters them. Directives in Angular are broadly classified into three types: component directives, attribute directives, and structural directives.
Component Directives: Component directives are the building blocks of Angular applications. They create reusable components with their own templates, styles, and logic. They are declared using the @Component
decorator and can be represented as elements in HTML with child elements. Component directives can communicate with other components using inputs and outputs.
Attribute Directives: Attribute directives modify the behavior or appearance of an HTML element. They are typically used as attributes on HTML elements. Attribute directives are declared using the @Directive
decorator and can be applied as attributes on HTML elements to apply visual transformations or change behavior.
Structural Directives: Structural directives allow dynamic manipulation of the DOM structure by adding, removing, or manipulating elements based on certain conditions. They are denoted by an asterisk (*) prefix in Angular syntax. Angular provides three built-in structural directives: ngIf
, ngFor
, and ngSwitch
.
Creating Custom Directives
Creating custom directives in Angular is a straightforward process. Let's get started by creating our first custom attribute directive for setting the font size of HTML elements. Here's how you can implement it:
Create new directive using the below command,
ng generate directive fontsize
This will create two files fontsize.directive.ts
and fontsize.directive.spec.ts
. Also, it imports this directive to module.ts
and includes it in the declaration section as follows,
import { FontsizeDirective } from './fontsize.directive';
@NgModule({
declarations: [
FontsizeDirective
],
})
export class AppModule { }
The font size can be updated in the fortsize.directive.ts
file as,
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appFontsize]'
})
export class FontsizeDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'fontSize', 'small');
}
}
ElementRef
is for fetching the DOM element on which the style needs to be applied.
Finally, the selector appFontsize
is used in the .html file on a particular element for which the fontSize needs to be applied.
<p appFontsize>This is a paragraph</p>
<div appFontsize>This is a div</div>
Why Use Custom Directives Instead of styling using CSS?
From our above example you might get a question in your mind that why we cannot achieve the same using CSS. Font size can be set through styling using CSS. However, there are situations where using a custom attribute directive can provide benefits over using inline styles or CSS classes. Here are a few reasons why you might choose to create a custom directive for setting font size:
- If you need to dynamically adjust the font size based on certain conditions or data, a custom directive allows you to handle the logic in your component or template.
- By encapsulating the font size logic within a directive, you can easily reuse it across multiple components and templates.
- It promotes a cleaner and more modular code structure. Using a directive allows you to keep the font size logic separate from your component's business logic.
- A custom directive gives you more flexibility in programmatically manipulating the font size.
- Custom directives can be combined with other Angular features, such as template expressions or structural directives, to achieve more complex behavior. For example, you can conditionally apply the
appFontSize
directive usingngIf
or iterate over a list of font sizes usingngFor
.
While setting font size through CSS styles is a common approach, creating a custom directive allows you to leverage the full power of Angular to manipulate font size based on dynamic conditions and achieve greater reusability and modularity in your code. Here is an example to demonstrate the same,
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appFontsize]'
})
export class FontsizeDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
const elementType = this.el.nativeElement.tagName.toLowerCase();
if(elementType == "p")
{
this.renderer.setStyle(this.el.nativeElement, 'fontSize', 'small');
}
else
{
this.renderer.setStyle(this.el.nativeElement, 'fontSize', 'x-large');
}
}
So, in the example it can be observed that when the element type is paragraph
then font size is set to small and x-large for other elements. In the browser it looks like,
Conclusion
Custom directives in Angular provide a powerful way to extend and enhance the functionality of your applications. They allow you to create reusable components, manipulate the DOM, and encapsulate complex behaviors. By leveraging custom directives, you can achieve code reusability, maintainability, and improved developer productivity.
Throughout this blog, we explored the fundamentals of custom directives. We discussed their syntax, use cases, and how to create and use them in Angular applications. Custom directives offer a level of flexibility and control that enables you to create unique and tailored experiences for your users. They allow you to implement custom behaviors, apply fine-grained styling, and interact with the DOM in ways that are not possible with built-in Angular directives alone. By mastering the art of custom directives, you can unlock the full potential of Angular and take your application development to the next level. Whether you're building complex UI components, adding interactive features, or improving accessibility, custom directives empower you to create truly dynamic and customizable Angular applications.
Happy exploring!
Top comments (0)