Custom Directives in Angular 8 | Angular Directive Tutorial With Example

I think directives are the most important bit in an Angular application. There are 3 types of directive in Angular which is listed below.

  1. Component Directive
  2. Attribute Directive
  3. Structural Directive

Component Directive:

The component directive is something which is the core thing of angular application. We create components by using @Component decorator. The best example of component directive is AppComponent.

Attribute Directive:

Creating a directive is pretty similar to a component, we user @Directive decorator for creating the directives. Attribute directives are used as attributes of elements. Let me explain this with an example:

I wanted something like if I hover the mouse on paragraph then it's background should get changed. I also wanted to do something when someone clicks in the paragraph. Let's create a directive by name ParagraphColor by running below command. Once you run the below command, it'll automatically add the ParagraphColorDirective entry in declarations in the app.module.ts.

Here in the above code snippet, we have a directive whose selector is appParagraphColor. We have been used @HostListener to listen to mouse events.  We have created an object of ElementRef which will help us to set the background color of the paragraph.

In the above example, we have used mouseenter, mouseleave and click events. On mouse enter, we call the highlight function to set the background. We have passed/Input the color name from the component.

In the app component, we have defined the color name and passing the color to the directive in the below code.

appParagraphColor is the ParagraphColorDirective selector and we are passing the color name to the directive here.
attribute-directive-example
 Structural Directive: Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements. *ngIf and *ngFor are the best example of the structural directive.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *