A Look into Angular Directives

Satyaprakash Samantaray  Print 
17 Sep 2018
 
Intermediate
399

HTML doesn't support conditional attributes (if, if-else, switch etc.), loop statements (loops) and other attributes. Angular Directives are used to extend the power of existing Html markup by adding new attributes or tags. They change the appearance or behaviour of a DOM element.

In this article, I will show you the types of directives in Angular 6 and the basic examples for using these directives.

Types of Directives in Angular

  • Components

  • Attribute directives

  • Structural directives

  • Custom Directive

Components

Typically, Component is a directive with a template. @Component decorator extends the @Directive decorator with template-oriented features. A component class is declared using @Component decorator. @Component decorator contains metadata about the component i.e. selector, templateURL, styleUrls etc.

Component Example
import {Component} from '@angular/core' 
 
@Component({ 
 selector: 'app-root', 
 templateUrl: './app.component.html', 
 styleUrls: ['./app.component.css'] 
}) 
 
export class AppComponent{}

Attribute Directive

Attribute directives are used change the appearance or behaviour of an existing DOM element. ngStyle and ngClass are the commonly used example for attribute directives.

NgStyle

This is used to configure multiple inline styles for html element.

NgClass

This is used to set the class attribute of the html element to apply the style.

Example for NgStyle
 import { Component } from '@angular/core'; 
 
 @Component({ 
 selector: 'Satya-App', 
 template: `<button style='color:green' [ngStyle]="MyStyle()">Satyaprakash Samantaray</button>`
 }) 
 export class AppComponent { 
 isBold: boolean = true; 
 fontSize: number = 30; 
 isItalic: boolean = true; 
 
 MyStyle() { 
 let mystyles = { 
 'font-weight': this.isBold ? 'bold' : 'normal', 
 'font-style': this.isItalic ? 'italic' : 'normal', 
 'font-size.px': this.fontSize 
 }; 
 
 return mystyles; 
 } 
 } 
Code Description

Here I added a button control in template part with style sheet named MyStyle(). This MyStyle css method is defined as below.

 MyStyle() { 
 let mystyles = { 
 'font-weight': this.isBold ? 'bold' : 'normal', 
 'font-style': this.isItalic ? 'italic' : 'normal', 
 'font-size.px': this.fontSize 
 }; 
 
 return mystyles;
Output
Example for NgClass
 import { Component } from '@angular/core'; 
 
 @Component({ 
 selector: 'Satya-App', 
 template: `<button class='colorClass' [ngClass]='applyClasses()'>Satyaprakash Samantaray</button>`, 
 styles: [`.boldClass{ 
 font-weight:bold; 
 font-size : 30px; 
 } 
 
 .italicsClass{ 
 font-style:italic; 
 } 
 
 .colorClass{ 
 color:Red; 
 }`] 
 }) 
 export class AppComponent { 
 applyBoldClass: boolean = true; 
 applyItalicsClass: boolean = true; 
 
 applyClasses() { 
 let classes = { 
 boldClass: this.applyBoldClass, 
 italicsClass: this.applyItalicsClass 
 }; 
 
 return classes; 
 } 
 } 
Code Description

In this NgClass we are using class attribute of html element to apply styles.

 template: `<button class='colorClass' [ngClass]='applyClasses()'>Satyaprakash Samantaray</button>`,
Output

Structural Directive

Structural directive are used to alter layout by adding, removing, and replacing elements in DOM. Asterisk (*) is used when these directives are used with the HTML elements. *ngIf, *ngFor, *ngSwitch are some commonly used structural directive.

NgIf

It is used to create or remove a part of DOM tree depending on a condition.

NgFor

It is used for iteration like showing a list of items using loops.

NgSwitch

It can be used as a switch case in OOPS. It is used to select one case among various cases. Angular will add only the selected option html markup into the DOM.

Example for ngIf
 
 import { Component } from '@angular/core'; 
 
 @Component({ 
 selector: 'Satya-App', 
 template: `<div style='color:blue' *ngIf="true">You can See Satyaprakash....</div>`
 }) 
 export class AppComponent { 
 
 } 
Code Description

Here If ngif= true So, that the text will be visible on the web page.

 
 template: `<div style='color:blue' *ngIf="true">You can See Satyaprakash....</div>`
Output
Example for ngFor : TS Code
 
 import { Component } from '@angular/core'; 
 
 @Component({ 
 selector: 'Satya-App', 
 templateUrl: './app.component.html', 
 }) 
 export class AppComponent { 
 employees: any[] = [ 
 { 
 code: '1001', name: 'Satya', gender: 'Male', 
 annualSalary: 5500, dateOfBirth: '25/6/1988' 
 }, 
 { 
 code: '1002', name: 'Mohit', gender: 'Male', 
 annualSalary: 5700.95, dateOfBirth: '9/6/1982' 
 }, 
 { 
 code: '1003', name: 'Rohit', gender: 'Male', 
 annualSalary: 5900, dateOfBirth: '12/8/1979' 
 }, 
 { 
 code: '1004', name: 'Satyaprakash Samantaray', gender: 'Female', 
 annualSalary: 6500.826, dateOfBirth: '14/10/1980' 
 }, 
 ]; 
 } 
Code Description

I have created a class named employees and insert values to its corresponding properties.

 
 employees: any[] = [ 
 { 
 code: '1001', name: 'Satya', gender: 'Male', 
 annualSalary: 5500, dateOfBirth: '25/6/1988' 
 },
 
Example for ngFor : Html Code
 
 <!DOCTYPE html> 
 <html> 
 <head> 
 <title></title> 
 <meta charset="utf-8" /> 
 <style> 
 table { 
 font-family: arial, sans-serif; 
 border-collapse: collapse; 
 width: 100%; 
 } 
 
 td, th { 
 border: 1px solid #dddddd; 
 text-align: left; 
 padding: 8px; 
 } 
 
 tr:nth-child(even) { 
 background-color: #dddddd; 
 } 
 </style> 
 </head> 
 <body> 
 <table align="center" border="1" cellpadding="4" cellspacing="4"> 
 <thead> 
 <tr> 
 <th style="background-color: Yellow;color: blue">Code</th> 
 <th style="background-color: Yellow;color: blue">Name</th> 
 <th style="background-color: Yellow;color: blue">Gender</th> 
 <th style="background-color: Yellow;color: blue">Annual Salary</th> 
 <th style="background-color: Yellow;color: blue">Date of Birth</th> 
 </tr> 
 </thead> 
 <tbody> 
 <tr *ngFor='let employee of employees'> 
 <td>{{employee.code}}</td> 
 <td>{{employee.name}}</td> 
 <td>{{employee.gender}}</td> 
 <td>{{employee.annualSalary}}</td> 
 <td>{{employee.dateOfBirth}}</td> 
 </tr> 
 <tr *ngIf="!employees || employees.length==0"> 
 <td colspan="5"> 
 No employees to show in the page.... 
 </td> 
 </tr> 
 </tbody> 
 </table> 
 </body> 
 </html> 
Code Description

Here NgFor is usded to display a list of items using repetitive loops that is data of employees class.

 
 <tr *ngFor='let employee of employees'> 
 <td>{{employee.code}}</td> 
 <td>{{employee.name}}</td> 
 <td>{{employee.gender}}</td> 
 <td>{{employee.annualSalary}}</td> 
 <td>{{employee.dateOfBirth}}</td> 
 </tr> 
Output
app.component.ts with NgSwitch implementation
 import { Component } from '@angular/core'; 
 
 @Component({ 
 selector: 'Satya-App', 
 template: `<h2>{{title}}</h2> 
 <p *ngIf="showElement">Show Element</p> 
 <div [ngSwitch]="inpvalue"> 
 <p style='color:blue' *ngSwitchCase="1">You have selected M S Dhoni</p> 
 <p style='color:blue' *ngSwitchCase="2">You have selected Sachin Tendulkar</p> 
 <p style='color:blue' *ngSwitchCase="3">You have selected Satyaprakash Samantaray</p> 
 <p style='color:red' *ngSwitchDefault>Sorry! Invalid selection....</p> 
 </div>` 
 }) 
 export class AppComponent { 

 inpvalue: number = 3; 
 } 
Code Description

You can display one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM. Here we are using ngswitchcase to apply switch case and ngswitchdefault is for invalid selection. Using ngswitch directive we can show output by passing value of inpvalue property in AppComponent class.

Output

For valid selection >>

For Invalid selection >>

You can check code compilation status in command prompt during change in code using visual studio.

Difference between structural directive and attribute directive

Structural directives are used for adding, removing, and replacing elements in DOM. Whereas attribute directives are used to change the appearance or behavior of an existing element.

Custom Attribute Directive

Custom attribute directive can be created by using @Directive decorator. Custom attribute directive can be used to modify background color, text information of an HTML element and that process is called as host element. To change UI look angular provides ElementRef class that can directly access DOM.

Creating a Custom Directive

Let's create a folder under app called directives. Under directives create a file called red.directive.ts as give below:

 
 import { Directive, ElementRef } from '@angular/core';
 
 @Directive({ 
 selector: '[ColorRed]' 
 })
 export class MyCustomDirective {
 constructor(elRef: ElementRef) {
 elRef.nativeElement.style.color = 'darkred';
 }
 } 
Code Description

Make a directive named as myRed directive. We can use it with HTML element such as <p> and <div>, the text color within that element will be red.The @Directive is used as an angular directive to retrieve directive configuration metadata. To use our custom directive in our angular project follow below code to set-up in application module.

 
 import { BrowserModule } from '@angular/platform-browser';
 import { NgModule } from '@angular/core';
 
 import { AppComponent } from './app.component';
 import { MyRedDirective } from './directives/red.directive';
 
 @NgModule({
 declarations: [
 AppComponent,
 MyCustomDirective
 ],
 imports: [
 BrowserModule
 ],
 providers: [],
 bootstrap: [AppComponent]
 })
 export class AppModule { }
app.component.ts
 
 import { Component } from '@angular/core';
 
 @Component({
 selector: 'Satya-App',
 templateUrl: './app.component.html'
 })
 export class AppComponent { 
 txtsize = '25px';
 colors = ['red', 'blue', 'orange'];
 myColor = '';
 }
app.component.html
 
 <!DOCTYPE html> 
 <html> 
 <head> 
 <title></title> 
 <meta charset="utf-8" /> 
 <style> 
 table { 
 font-family: arial, sans-serif; 
 border-collapse: collapse; 
 width: 100%; 
 } 
 
 td, th { 
 border: 1px solid #dddddd; 
 text-align: left; 
 padding: 8px; 
 } 
 
 tr:nth-child(even) { 
 background-color: #dddddd; 
 } 
 </style> 
 </head> 
 <body> 
 <p ColorRed>Custom Attribute Directive By Satyaprakash</p> 
 </body> 
 </html> 
Code Description

we are ready to use our directive in the HTML template. Find the code snippet.

 
 <body> 
 <p ColorRed>Custom Attribute Directive By Satyaprakash</p> 
 </body>
app.module.ts
 
 import { BrowserModule } from '@angular/platform-browser';
 import { NgModule } from '@angular/core';
 
 import { AppComponent } from './app.component';
 import { MyRedDirective } from './directives/red.directive';
 
 @NgModule({
 declarations: [
 AppComponent,
 MyCustomDirective
 ],
 imports: [
 BrowserModule
 ],
 providers: [],
 bootstrap: [AppComponent]
 })
 export class AppModule { }
Code Description

Here I import custom attribute directive reference to configure custom attribute what I have created.

 
 import { MyRedDirective } from './directives/red.directive';
 
 @NgModule({
 declarations: [
 AppComponent,
 MyCustomDirective
 ],
 
Output
Summary

In this article, you learned about the various types of directives in Angular with example. I hope, you will find it useful when you will work with your Angular Application.

Hands-on Learning
Free Interview Books
 
+