With custom Angular directives, you can add your own HTML tags or attributes and corelate them with particular feature. This grants you encapsulate difficult logic and features into a single directive, which can be further reused throughout your angular application.
In general, there are 3 types of directives: structural, attribute and components.
If you wish to remove or add elements from the DOM, then you will depend on structural directives. Here is a couple of examples for structural directives: *ngSwitch
, *ngFor
and *ngIf
.
If you wish to alter the behaviour or styling of an element, you go for attribute directives.
We are going to take a look at an example to create a custom directive in Angular, It will apply rounded corners to HTML elements. I’ll take the help of appRoundBlock
directive.
In order to remove strict type warnings or errors make sure to set
“strict”: false
and"strictTemplates": false
under compilerOptions and angularCompilerOptions properties in tsconfig.json file.
Angular 16 Custom Directives Example
To create a custom directive in Angular, you need to use the @Directive decorator. This decorator is used to define the selector for your directive, which specifies how the directive will be used in your HTML templates.
Once you have defined a custom directive, you can use it in your HTML templates by adding the directive’s selector as an attribute or element. This will apply the functionality and behavior defined in the directive to the corresponding HTML element.
We are going to import Renderer2
, ElementRef
and Directive
from @angular/core
. Then we will use the renderer to set the style of the element according to our need:
Run the following command to generate custom directive in Angular app.
ng generate directive roundBlock
round-block.directive.ts
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appRoundBlock]'
})
export class RoundBlockDirective {
constructor(renderer: Renderer2, elmRef: ElementRef) {
renderer.setStyle(elmRef.nativeElement, 'border-radius', '100px');
}
}
We have wrapped the selector in brackets: [appRoundBlock]
. This is to turn it into a border-radius directive.
Now let’s check this out in our app module.
When we ran the command to create custom directives in an Angular app, that command automatically registered custom directive in app module file.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { RoundBlockDirective } from './round-block.directive';
@NgModule({
declarations: [
AppComponent,
RoundBlockDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
How to Use Custom Directive in our Angular Template?
We make use of the directive present in the template. We can easily use attribute directive in the template as we have shown below:
Update code in app.component.html file:
<div class="demo-block" appRoundBlock>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </div>
You can open the console and inspect the div, the border-radius class appeared on the element.
Set Up Dynamic Values in Custom Directives in Angular
Well, our appRoundBlock
directive isn’t that smart. With the help of a style binding, we could have easily provided values to border-radius.
Therefore, we are going to improve the directive by making it possible for us to pass values through to the directive.
round-block.directive.ts
import { Directive, ElementRef, Input, Renderer2, OnInit } from '@angular/core';
@Directive({
selector: '[appRoundBlock]'
})
export class RoundBlockDirective implements OnInit {
@Input() appRoundBlock: string;
constructor(
private elmRef: ElementRef,
private renderer: Renderer2)
{ }
ngOnInit() {
let roundVal = `${this.appRoundBlock}`;
this.renderer.setStyle(this.elmRef.nativeElement, 'border-radius', roundVal);
}
}
This is how we gain use it in html component.
Update code in app.component.html
file:
<div class="demo-block" [appRoundBlock]="'30px'">Angular Custom Directive Example</div>
The following command will start a development server, compile and run your app.
ng serve --open
Conclusion
Custom directives in Angular are powerful tools that allow you to create reusable components and extend the functionality of HTML elements. They provide a way to encapsulate complex logic and behavior, making your code more modular and maintainable.