How do I create a directive in Angular?

In Angular, you can create a custom directive to extend the functionality of HTML elements. Here’s how to create a directive:

  1. Open the terminal and navigate to your Angular project directory.
  2. 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
  1. The Angular CLI will generate a new file for the directive, for example, mydirective.directive.ts. Open the file and define the directive’s selector and logic. A basic directive definition might look like this:
import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appMydirective]'
})
export class MydirectiveDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
  }
}
  1. 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 { MydirectiveDirective } from './mydirective.directive';

Then, add the directive to the declarations array:

declarations: [
  MydirectiveDirective
]
  1. 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.