Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is −
The above files, i.e., custom-directive.directive.spec.ts and custom-directive.directive.ts get created and the app.module.ts file is updated.
Open Custom-directive.directive.ts file and follow these steps:-
- Import the necessary modules:
Directive
,ElementRef
, andRenderer2
from@angular/core
- Create a new class and decorate it with
@Directive
. The decorator takes an object with aselector
property, which is the name of the directive that you will use in your template. - Inject
ElementRef
andRenderer2
in the constructor of your class. These will allow you to manipulate the element that the directive is applied to. - Add logic to the class to manipulate the element as needed. For example, you could add an event listener to the element or change its styling.
- Finally, you can use the directive in your template by adding the selector as an attribute on an element.
It’s a basic example, You can also pass parameters to the directive using @Input or @Output decorators. You can also create an attribute directive as well as structural directive.