Angular

Custom Attribute Directives

In this post I am going to show how to build custom attribute directive. If you are looking for general information about angular directives, check my previous post here.

To build your own custom directive, the first thing you have to do is to create a new typescript file. Next import Directive, ElementRef and Renderer2 from @angular/core.
After that create a new class and mark it as angular directive by using @Directive decorator. Specify selector name and wrap it into brackets. Afterwards, create constructor and inject into it ElementRef and Renderer2. In the end define how the directive impacts on HTML element. In this example it changes font color and size:

customFont.directive.ts

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

@Directive({ selector: '[customFont]' })
export class CustomFontDirective {
    constructor(elem: ElementRef, renderer: Renderer2) {
       renderer.setStyle(elem.nativeElement, 'font-size', '20px');
       renderer.setStyle(elem.nativeElement, 'color', 'blue');
    }
}

To make our directive work we have to declare it in appropriate module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FormsModule }   from '@angular/forms';
import { AppComponent } from './app.component';
import { CustomFontDirective } from './customFont.directive';

@NgModule({
  declarations: [
    CustomFontDirective,
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

The usage of the directive could be as follows:

  <button customFont
           class="btn btn-default"
           type="submit">
           Send
  </button>   

Leave a Reply

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