Angular Directives

Angular Directives





Directives in Angular are like some instructions in the DOM. They are useful to extend the power of the HTML attributes. Directives can change your DOM layout, also can change the appearance or behavior of an Html element.  

Directives are decorated with the @Directive decorator.

For example, Angular provides you a ngIf directive that is used when you want to display or hide an Html element based on some condition. Also, there is ngStyle directive which you can use to apply CSS to the Html element.
 
There are so many built-in directives that Angular provides you. You can also create your own custom directives in Angular.

Note: Angular components are also a type of Directive with a template.


There are 3 kinds of Directives in Angular:

1. Attribute directives
2. Structural directives
3. Components - Directive with a template


Create an Attribute Directive 

Use the below Angular CLI command to create a directive:

ng generate directive highlight

This command should create a new directive. The newly created directive must be declared in the root app module. As we have created the directive using Angular CLI, it itself declare it in the root module.

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor() { }

}


Note: As you can see, the selector for the directive is with the square brackets [] that makes it an attribute selector. Angular finds the elements in the template that has the attribute name "appHighlight" and applies the logic of the directive class to that element.


Directive Example:

highlight.directive.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(private eleRef: ElementRef) {
     this.highlight('orange')
  }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow')
  }

  @HostListener('mouseleave') onMouseLeave(){
    this.highlight('orange')
  }

  private highlight(color: string) {
    this.eleRef.nativeElement.style.backgroundColor = color

  }

}


app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template:
    `
     <p appHighlight> Change my color </p>

  `
  ,
  styleUrls: ['./app.component.css']
})

export class AppComponent {

}






Post a Comment

0 Comments