Simple Custom Directive in Angular 2


Custom Directive

Directives are similar to components, components are just directives with a view attached. There are three kinds of directives in Angular 2 as given below.

a. components — To create HTML template.
b. attribute — To changes the appearance and behavior of DOM element(NgStyle, NgClass).
c. structural — To add and remove DOM elements(NgFor, NgIf).

Prerequisites

Angular Cli must be installed if not installed check out my previous article “Install and run Angular 2 apps using Angular CLI”.
Some basic knowledge on Html, Css, Javascript, Oops.

Create a new Custom Attribute Directive

Today we are going to create a directive that is used to change font color.

Using command :

ng generate directive fontcolor

Manually :

Create below file inside app folder

fontcolor.directive.ts

since we created fontcolor directive manually, it needs to be added in our module file to expose this service to outside world connected with that module.

In our example we are going to add it in app.module.ts file

Analysing fontcolor.directive.ts

import { Directive, ElementRef, Renderer } from ‘@angular/core’;

Imported the Directive decorator, ElementRef used to get dom element, Renderer to set the element’s style from Angular core module.

@Directive({ selector: ‘[appFontcolor]’ })

@Directive() decorator will tell the angular that this file used to define custom directive.
{ selector: ‘[appFontcolor]’ } parameter inside @Directive() is the directive name we are going to use in our template(<div appFontcolor> Helloworld !!! </div>).

export class FontcolorDirective {
constructor(elem: ElementRef, renderer: Renderer) {
renderer.setElementStyle(elem.nativeElement, ‘color’, ‘#EEBA33’);
}
}

Final step : exported class in which ElementRef is used get the current dom element and Renderer is used to apply style to the selected element.

Implementation: if fontcolor directive is used in app component will be like below.

app.component.html

<div appFontcolor> Helloworld !!! </div>

Thanks you!!! Happy Coding


Angularjs

This will contain article about angular 2

SatheeshKumar Manoharan

Written by

Entrepreneur, Web miner, Traveller, Passionate driver, Mac addict, Share trader

Angularjs

Angularjs

This will contain article about angular 2

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade