In Angular, you can create a custom directive to extend the functionality of HTML elements. Here’s how to create a directive:
- Open the terminal and navigate to your Angular project directory.
- Run the following command to generate a new directive:
ng generate directive <directive-name>
Replace <directive-name>
with the name of your directive. For example, if you want to create a directive named “mydirective”, run the following command:
ng generate directive mydirective
- The Angular CLI will generate a new file for the directive, for example,
. Open the file and define the directive’s selector and logic. A basic directive definition might look like this:mydirective
.directive.ts
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appMydirective
]'
})
export class Mydirective
Directive {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
}
}
- Add the directive to the module: To use the new directive in your application, you need to add it to the module. Open the
app.module.ts
file and import the directive:
import {
Mydirective
Directive} from './mydirective.directive';
Then, add the directive to the declarations
array:
declarations: [
Mydirective
Directive
]
- Use the directive in your template: To use the new directive in your template, you can add it as an attribute to an HTML element. For example, if you want to use the “
mydirective
” directive, you can add the following attribute to an element:
<p appMydirective
>This text will be Displayed</p>
That’s it! Your custom directive is now ready to use in your Angular application.