How to implement and create custom directive?

Priti Jha
2 min readJan 18, 2023

--

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:-

  1. Import the necessary modules: Directive, ElementRef, and Renderer2 from @angular/core
  2. Create a new class and decorate it with @Directive. The decorator takes an object with a selector property, which is the name of the directive that you will use in your template.
  3. Inject ElementRef and Renderer2 in the constructor of your class. These will allow you to manipulate the element that the directive is applied to.
  4. 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.
  5. 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.

--

--

Priti Jha
Priti Jha

Written by Priti Jha

Senior front-end developer writing about Angular 8 , Ionic Framework ,Javascript, HTML, Css and all front end technology.

No responses yet