Directives are used in Angular to extend the capabilities of HTML elements and components. They are a method of adding behavior to DOM elements. Directives can be used to change the appearance or layout of elements, respond to user events, perform data binding, and do other things
Here’s a simple example of how to use a custom directive in Angular. Use the following command to add a new directive in your desired folder (take the terminal there):
ng g directive my-custom
The above code is a command used to generate a new Angular directive using the Angular CLI.
The command is made up of several parts:
ng: the command for the Angular CLI.
g: signifies for generate and it commands the CLI to generate a new file.
directive: signifies the type of file to generate, in this case, it is a directive.
my-custom: is the name of the directive. It is a convention to use a dash-separated naming for directives.
This command will create a new custom directive in the src/app/ directory. The CLI will also automatically add this directive to the declarations array in the @NgModule decorator of the app.module.ts file, making it available to use throughout the application.
This will create a new file for the directive with the directive’s selector as appMyCustomDirective using the @Directive decorator.
import { Directive } from '@angular/core';
@Directive({
selector: '[appMyCustomDirective]'
})
export class MyCustomDirective {
}
In the @NgModule decorator of the module where the directive will be used, add the directive to the declarations array.
import { MyCustomDirective } from './my-custom.directive';
@NgModule({
declarations: [MyCustomDirective],
imports...
providers...
})
export class AppModule { }
Add the directive’s selector as an attribute to an element to use it in a template.
<div appMyCustomDirective>You are using appMyCustomDirective</div>
This is an HTML element using a custom Angular directive named appMyCustomDirective. The directive has been applied to the div element by adding an attribute named appMyCustomDirective.
In summary, directives are used to increase the functionality of HTML elements and components. They can be both structural and component elements, and they can also control the DOM, respond to events, and perform data binding.