Angular Directives

  • Directive is a Js Class
  • It is declared as @directive
  • We have three directives as follows
    1. Component directive: this is the main class which has the details of processing , initiating and using a component at runtime.
    2. Structural directive: this directive is used to modify the dom elements. It start with *. For eg *ngIf , *ngFor
    3. Attribute directive: Used to change the look of the dom. We can create our own custom directive.

Custom Directive:

We can create a custom directive using below command.

	ng g directive custom	
Bellow SS show the output of above command.

custom-directive

As we see the custom.directive.ts and custom.directive.spec.ts are created and details are added to app.module.ts

Below code shows the how app.module.ts will look like after creating a custom directive.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MyfirstcomponentComponent } from './myfirstcomponent/myfirstcomponent.component';
import { CustomDirective } from './custom.directive';

@NgModule({
  declarations: [
    AppComponent,
    MyfirstcomponentComponent,
    CustomDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We can see from above code, a custom directive is imported and an entry is made in the declaration section.

Custom.directive.ts
import { Directive } from '@angular/core';

@Directive({
  selector: '[appCustom]'
})
export class CustomDirective {

  constructor() { }

}

Custom directive has a directive and a selector.

Lets use custom.directive inside app.component.html as below. As we can see appCustom is used as an attribute in a h1 tag.


<div class="content">
  <h1 appCustom ></h1>
  
  <button (click) = "myfun($event)"> 
    Click Me
  </button>
  <br>

Lets modify the custom.directive.ts as below to display the text using attribute directive.


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

@Directive({
  selector: '[appCustom]'
})
export class CustomDirective {

  constructor(Element: ElementRef) { 
    Element.nativeElement.innerText = "This text is inserted using custom directive";
  }

}

Bellow SS show the output on a browser

custom-directive-output

Subscribe Now