List Of Directives In Angular 6 And How To Use Them

Introduction
 
Angular is an open source project, which can be used freely, modified and shared by others. Angular is developed by Google. Angular is a typescript based front-end web application platform.
 
To know more details visit my below link >>
Description
 
In this session, I will show you how to use types of directives in an Angular 6 application.

There are four types of directives in Angular,
  • Components directives
  • Structural directives
  • Attribute directives
  • Custom Directive

Components directives

It is mainly used to specify the HTML templates. It is the most commonly-used directive in an Angular project. It is decorated with the @component decorator. This directive is a class. The component directive is used to specify the template/HTML for the Dom Layout. Its built-in is @component.

  • app.component.css: contains all the CSS styles for the component
  • app.component.html: contains all the HTML code used by the component to display itself
  • app.component.ts: contains all the code used by the component to control its behavior

You can also find the app.module.ts file, which is used to define an Angular module.

A root component is the first Angular component that gets bootstrapped when the application runs. Two things are special about this component:

First, if you open the application module file src/app/app.module.ts

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppComponent } from './app.component';  
  5.   
  6. @NgModule({  
  7.   declarations: [  
  8.     AppComponent  
  9.   ],  
  10.   imports: [  
  11.     BrowserModule  
  12.   ],  
  13.   providers: [],  
  14.   bootstrap: [AppComponent]  
  15. })  
  16. export class AppModule { }  

You'll notice that, it's added to the bootstrap array of the module definition.

Second, if you open the src/index.html file (the first file that gets rendered when you visit the application URL) of the application:

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>Angular6Project</title>  
  6.   <base href="">  
  7.   
  8.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.   <link rel="icon" type="image/x-icon" href="favicon.ico">  
  10. </head>  
  11. <body>  
  12.   <Satya-App>Loading AppComponent, Please wait....</Satya-App>  
  13. </body>  
  14. </html>  

You'll notice that it's called inside the document <body> tag.

Starting with the application root component, all the other child components (the tree) will be loaded.

Now, let's open the component file src/app/app.component.ts,

  1. import { Component } from '@angular/core';    
  2.     
  3. @Component({    
  4.     selector: 'Satya-App',    
  5.     template: `<h2>{{title}}</h2>      
  6. <p *ngIf="showElement">Show Element</p>      
  7. <div [ngSwitch]="inpvalue">      
  8. <p style='color:blue'  *ngSwitchCase="1">You have selected M S Dhoni</p>      
  9. <p style='color:blue'  *ngSwitchCase="2">You have selected Sachin Tendulkar</p>      
  10. <p style='color:blue'  *ngSwitchCase="3">You have selected Satyaprakash Samantaray</p>     
  11. <p style='color:red'  *ngSwitchDefault>Sorry! Invalid selection....</p>      
  12. </div>`      
  13. })    
  14. export class AppComponent {    
  15.     
  16.     inpvalue: number = 4;    
  17. }    

First, we import the Component class from @angular/core. Then we use it to decorate the AppComponent class which transforms it to a component. The component decorator takes this information,

The selector contains the name of the tag that can be used to create this component.

The templateUrl contains the relative URL/path to the HTML template to be used as the view.

The styleUrls contains the array of CSS styles to be used for styling the component

The AppComponent has a variable title which has a string value. If you look in the component HTML template src/app/app.component.html,

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <title></title>    
  5.     <meta charset="utf-8" />    
  6.     <style>    
  7.       table {    
  8.           font-family: arial, sans-serif;    
  9.           border-collapse: collapse;    
  10.           width: 100%;    
  11.       }    
  12.       
  13.       td, th {    
  14.           border: 1px solid #dddddd;    
  15.           text-align: left;    
  16.           padding: 8px;    
  17.       }    
  18.       
  19.       tr:nth-child(even) {    
  20.           background-color: #dddddd;    
  21.       }            
  22.   </style>   
  23. </head>    
  24. <body>    
  25.     <table align="center" border="1" cellpadding="4" cellspacing="4">    
  26.         <thead>    
  27.             <tr>    
  28.                 <th style="background-color: Yellow;color: blue">Code</th>    
  29.                 <th style="background-color: Yellow;color: blue">Name</th>    
  30.                 <th style="background-color: Yellow;color: blue">Gender</th>    
  31.                 <th style="background-color: Yellow;color: blue">Annual Salary</th>    
  32.                 <th style="background-color: Yellow;color: blue">Date of Birth</th>    
  33.             </tr>    
  34.         </thead>    
  35.         <tbody>    
  36.             <tr *ngFor='let employee of employees'>    
  37.                 <td>{{employee.code}}</td>    
  38.                 <td>{{employee.name}}</td>    
  39.                 <td>{{employee.gender}}</td>    
  40.                 <td>{{employee.annualSalary}}</td>    
  41.                 <td>{{employee.dateOfBirth}}</td>    
  42.             </tr>    
  43.             <tr *ngIf="!employees || employees.length==0">    
  44.                 <td colspan="5">    
  45.                     No employees to show in the page....    
  46.                 </td>    
  47.             </tr>    
  48.         </tbody>    
  49.     </table>    
  50. </body>    
  51. </html>    

You can notice that we are using the curly braces “” to display the value of title. This is what's called data binding.

Angular 6 application is a tree of components with a root component. A component controls a part of the web application screen. It consists of JavaScript (or precisely TypeScript) code, HTML code and CSS. If you are familiar with the MVC (Model-View-Controller) architecture or design pattern, each component actually uses the same architecture: the component's code represents the controller and the HTML code (with CSS) represents the view.

You can create a component in Angular 6 using the @Component() decorator which can be imported from @angular/core. You simply decorate a TypeScript class with the @Component() decorator that takes information about the HTML view to use for the component and the CSS styles. For the code which controls the component, it's encapsulated inside the class.

@component decorator

It provides metadata that determines how the component should be processed, instantiated and used at runtime.

Code Ref. of app.component.ts

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'Angular 6 App By Satyaprakash';  
  10. }  

But I modified the code as below,

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'Satya-App',  
  5.   template: '<h1>{{name}}</h1>'  
  6. })  
  7. export class AppComponent {  
  8.   name: string = "Angular 6 By Satyaprakash"  
  9. }  

Code Description

In decorator part that is @component is the component decorator. I customized my selector Satya-app to map in HTML files. In the template, I put the name property which will fetch its value from the name string from AppComponent class.

Then type following code in Index.html

Code Ref

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>Angular6Project</title>  
  6.   <base href="">  
  7.   
  8.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.   <link rel="icon" type="image/x-icon" href="favicon.ico">  
  10. </head>  
  11. <body>  
  12.   <Satya-App>Loading AppComponent, Please wait....</Satya-App>  
  13. </body>  
  14. </html>  

Code Description

Here I put the selector for mapping.

  1. <body>  
  2.   <Satya-App>Loading AppComponent, Please wait....</Satya-App>  
  3. </body>  

OUTPUT

Initially the page will look like this:
 
List of Directives in Angular 6 

Then the result will be shown like this.

List of Directives in Angular 6 

Attribute Directive

Attribute directive is used to change/modify the behavior of the HTML element in the Dom Layout. Its built-in type is NgStyle, NgClass. it is used to change the attributes of the existing HTML element. NgClass, NgStyle are the most used attribute directives.

NgStyle

NgStyle directive is similar to one of the data binding techniques called style binding in Angular. The main point is NgStyle is used to set multiple inline styles for the HTML element.

NgClass

It is similar to NgStyle attribute but here it is using the class attribute of the HTML element to apply the style.

Code Ref. of app.component.ts for NgStyle
  1. import { Component } from '@angular/core';    
  2.     
  3. @Component({    
  4.     selector: 'Satya-App',    
  5.     template: `<button style='color:green' [ngStyle]="MyStyle()">Satyaprakash Samantaray</button>`  
  6. })    
  7. export class AppComponent {    
  8.     isBold: boolean = true;    
  9.     fontSize: number = 30;    
  10.     isItalic: boolean = true;    
  11.     
  12.     MyStyle() {    
  13.         let mystyles = {    
  14.             'font-weight'this.isBold ? 'bold' : 'normal',    
  15.             'font-style'this.isItalic ? 'italic' : 'normal',    
  16.             'font-size.px'this.fontSize    
  17.         };    
  18.     
  19.         return mystyles;    
  20.     }    
  21. }    

Code Description

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

  1. MyStyle() {    
  2.         let mystyles = {    
  3.             'font-weight'this.isBold ? 'bold' : 'normal',    
  4.             'font-style'this.isItalic ? 'italic' : 'normal',    
  5.             'font-size.px'this.fontSize    
  6.         };    
  7.     
  8.         return mystyles;  

OUTPUT

List of Directives in Angular 6

Code Ref. of app.component.ts for NgClass,

  1. import { Component } from '@angular/core';    
  2.     
  3. @Component({    
  4.     selector: 'Satya-App',    
  5.     template: `<button class='colorClass' [ngClass]='applyClasses()'>Satyaprakash Samantaray</button>`,    
  6.     styles: [`.boldClass{    
  7.                 font-weight:bold;    
  8.                   font-size : 30px;    
  9.             }    
  10.     
  11.             .italicsClass{    
  12.                 font-style:italic;    
  13.             }    
  14.     
  15.             .colorClass{    
  16.                 color:Red;               
  17.  }`]    
  18. })    
  19. export class AppComponent {    
  20.     applyBoldClass: boolean = true;    
  21.     applyItalicsClass: boolean = true;    
  22.     
  23.     applyClasses() {    
  24.         let classes = {    
  25.             boldClass: this.applyBoldClass,    
  26.             italicsClass: this.applyItalicsClass    
  27.         };    
  28.     
  29.         return classes;    
  30.     }    
  31. }    

Code Description

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

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

OUTPUT

List of Directives in Angular 6

Structural Directive

The structural directive is used to add or remove the HTML Element in the Dom Layout, typically by adding, removing, or manipulating elements... Its built-in types are *NgIf,*NgFor,*NgSwitch. Structural directives are easy to recognize by using an asterisk (*).

Difference between the structural directive and attribute directive

The structural directive is used to add or remove the Dom Element itself in the Dom Layout, whereas attribute directives are used to just change the attribute or appearance of the Dom element.

Types of built-in structural directive

  • NgIf
  • NgFor
  • NgSwitch

NgIf

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

NgFor

It is used to customize data display. It is mainly used for displaying a list of items using repetitive loops.

NgSwitch

It is like the JavaScript switch. It can display one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM.

Code Ref. of app.component.ts for implementation of NgIf
  1. import { Component } from '@angular/core';    
  2.     
  3. @Component({    
  4.     selector: 'Satya-App',    
  5.     template: `<div style='color:blue' *ngIf="true">You can See Satyaprakash....</div>`  
  6. })    
  7. export class AppComponent {    
  8.       
  9. }    

Code Description

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

  1. template: `<div style='color:blue' *ngIf="true">You can See Satyaprakash....</div>`  

OUTPUT

List of Directives in Angular 6

Code Ref. of app.component.ts for implementation of NgFor,

  1. import { Component } from '@angular/core';    
  2.     
  3. @Component({    
  4.     selector: 'Satya-App',    
  5.     templateUrl: './app.component.html',      
  6. })    
  7. export class AppComponent {    
  8.     employees: any[] = [    
  9.         {    
  10.             code: '1001', name: 'Satya', gender: 'Male',    
  11.             annualSalary: 5500, dateOfBirth: '25/6/1988'    
  12.         },    
  13.         {    
  14.             code: '1002', name: 'Mohit', gender: 'Male',    
  15.             annualSalary: 5700.95, dateOfBirth: '9/6/1982'    
  16.         },    
  17.         {    
  18.             code: '1003', name: 'Rohit', gender: 'Male',    
  19.             annualSalary: 5900, dateOfBirth: '12/8/1979'    
  20.         },    
  21.         {    
  22.             code: '1004', name: 'Satyaprakash Samantaray', gender: 'Female',    
  23.             annualSalary: 6500.826, dateOfBirth: '14/10/1980'    
  24.         },    
  25.     ];    
  26. }    

Code Description

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

  1. employees: any[] = [    
  2.         {    
  3.             code: '1001', name: 'Satya', gender: 'Male',    
  4.             annualSalary: 5500, dateOfBirth: '25/6/1988'    
  5.         },  

Code ref. of app.component.html for implementation of NgFor,

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <title></title>    
  5.     <meta charset="utf-8" />    
  6.     <style>    
  7.       table {    
  8.           font-family: arial, sans-serif;    
  9.           border-collapse: collapse;    
  10.           width: 100%;    
  11.       }    
  12.       
  13.       td, th {    
  14.           border: 1px solid #dddddd;    
  15.           text-align: left;    
  16.           padding: 8px;    
  17.       }    
  18.       
  19.       tr:nth-child(even) {    
  20.           background-color: #dddddd;    
  21.       }            
  22.   </style>   
  23. </head>    
  24. <body>    
  25.     <table align="center" border="1" cellpadding="4" cellspacing="4">    
  26.         <thead>    
  27.             <tr>    
  28.                 <th style="background-color: Yellow;color: blue">Code</th>    
  29.                 <th style="background-color: Yellow;color: blue">Name</th>    
  30.                 <th style="background-color: Yellow;color: blue">Gender</th>    
  31.                 <th style="background-color: Yellow;color: blue">Annual Salary</th>    
  32.                 <th style="background-color: Yellow;color: blue">Date of Birth</th>    
  33.             </tr>    
  34.         </thead>    
  35.         <tbody>    
  36.             <tr *ngFor='let employee of employees'>    
  37.                 <td>{{employee.code}}</td>    
  38.                 <td>{{employee.name}}</td>    
  39.                 <td>{{employee.gender}}</td>    
  40.                 <td>{{employee.annualSalary}}</td>    
  41.                 <td>{{employee.dateOfBirth}}</td>    
  42.             </tr>    
  43.             <tr *ngIf="!employees || employees.length==0">    
  44.                 <td colspan="5">    
  45.                     No employees to show in the page....    
  46.                 </td>    
  47.             </tr>    
  48.         </tbody>    
  49.     </table>    
  50. </body>    
  51. </html>    

Code Description

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

  1. <tr *ngFor='let employee of employees'>    
  2.                 <td>{{employee.code}}</td>    
  3.                 <td>{{employee.name}}</td>    
  4.                 <td>{{employee.gender}}</td>    
  5.                 <td>{{employee.annualSalary}}</td>    
  6.                 <td>{{employee.dateOfBirth}}</td>    
  7.             </tr>   

OUTPUT

List of Directives in Angular 6

Code Ref. of app.component.ts for implementation of NgSwitch,

  1. import { Component } from '@angular/core';    
  2.     
  3. @Component({    
  4.     selector: 'Satya-App',    
  5.     template: `<h2>{{title}}</h2>      
  6. <p *ngIf="showElement">Show Element</p>      
  7. <div [ngSwitch]="inpvalue">      
  8. <p style='color:blue'  *ngSwitchCase="1">You have selected M S Dhoni</p>      
  9. <p style='color:blue'  *ngSwitchCase="2">You have selected Sachin Tendulkar</p>      
  10. <p style='color:blue'  *ngSwitchCase="3">You have selected Satyaprakash Samantaray</p>     
  11. <p style='color:red'  *ngSwitchDefault>Sorry! Invalid selection....</p>      
  12. </div>`      
  13. })    
  14. export class AppComponent {    
  15.     
  16.     inpvalue: number = 3;    
  17. }    

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 the value of inpvalue property in AppComponent class.

OUTPUT

For valid selection >>

List of Directives in Angular 6

For Invalid selection >>
List of Directives in Angular 6

You can check code compilation status in command prompt during the change in code using Visual Studio.

List of Directives in Angular 6

Custom Attribute

We can create custom attribute directives and custom structural directives using a @Directive decorator. Using custom attribute directive we can change appearances such as text color, background color and font size of the body of an HTML element that can be called host element. To change appearance angular provides ElementRef class that can directly access DOM.

Benefits of using custom directive:

It is vulnerable to XSS attacks when we directly use ElementRef in our application. It is better to create a custom directive and use ElementRef inside directive to change appearance or behavior of the host element.

Steps to be followed to create custom attribute directive

  1. Create a class decorated with @Directive.
  2. Assign the attribute directive name to the selector metadata of @Directive decorator.
  3. Use ElementRef class to access DOM to change host element appearance and behavior.
  4. Use @Input() decorator to accept user input in our custom directive.
  5. Use @HostListener() decorator to listen to events in custom attribute directive.
  6. Configure custom attribute directive class in application module in the declarations metadata of @NgModule.

Steps to be followed for customization of project structure and code

Create a folder under app called directives. Under directives create a file called red.directive.ts.

Code Ref. ofred.directive.ts

  1. import { Directive, ElementRef } from '@angular/core';  
  2.   
  3. @Directive({   
  4.      selector: '[myRed]'   
  5. })  
  6. export class MyRedDirective {  
  7.     constructor(elRef: ElementRef) {  
  8.        elRef.nativeElement.style.color = 'red';  
  9.     }  
  10. }   

Code Description

We are creating a directive named as myRed directive. When we use it with HTML elements such as <p> and <div>, the text color within that element will be red.

The class should be decorated with @Directive. The role of @Directive is to mark a class as an angular directive and to collect directive configuration metadata.

To define a directive name, we need to use metadata selector and assign a directive name enclosed with the bracket [ ], for example [myRed]. We should not use any keyword as a directive name which is reserved by angular and we should also not start the directive name with ng.

Create a constructor in the class to get the instance of ElementRef by dependency injection. Using ElementRef we can access the DOM element and can change their appearance and behavior.

To use our custom directive anywhere in our angular application, we need to configure it in application module in the same way as we configure the component.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { MyRedDirective }  from './directives/red.directive';  
  6.   
  7. @NgModule({  
  8.   declarations: [  
  9.     AppComponent,  
  10.     MyRedDirective  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule  
  14.   ],  
  15.   providers: [],  
  16.   bootstrap: [AppComponent]  
  17. })  
  18. export class AppModule { }  

Code Ref. of app.component.ts

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.    selector: 'Satya-App',  
  5.    templateUrl: './app.component.html'  
  6. })  
  7. export class AppComponent {   
  8.    txtsize = '25px';  
  9.    colors = ['CYAN''GREEN''YELLOW'];  
  10.    myColor = '';  
  11. }  

Code Ref. Of app.component.html

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <title></title>    
  5.     <meta charset="utf-8" />    
  6.     <style>    
  7.       table {    
  8.           font-family: arial, sans-serif;    
  9.           border-collapse: collapse;    
  10.           width: 100%;    
  11.       }    
  12.       
  13.       td, th {    
  14.           border: 1px solid #dddddd;    
  15.           text-align: left;    
  16.           padding: 8px;    
  17.       }    
  18.       
  19.       tr:nth-child(even) {    
  20.           background-color: #dddddd;    
  21.       }            
  22.   </style>   
  23. </head>    
  24. <body>    
  25.   <p myRed>Custom Attribute Directive By Satyaprakash</p>   
  26. </body>    
  27. </html>    

Code Description

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

  1. <body>    
  2.   <p myRed>Custom Attribute Directive By Satyaprakash</p>   
  3. </body>  

Code ref. of app.module.ts

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppComponent } from './app.component';  
  5. import { MyRedDirective }  from './directives/red.directive';  
  6.   
  7. @NgModule({  
  8.   declarations: [  
  9.     AppComponent,  
  10.     MyRedDirective  
  11.   ],  
  12.   imports: [  
  13.     BrowserModule  
  14.   ],  
  15.   providers: [],  
  16.   bootstrap: [AppComponent]  
  17. })  
  18. export class AppModule { }  

Code Description

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

  1. import { MyRedDirective }  from './directives/red.directive';  
  2.   
  3. @NgModule({  
  4.   declarations: [  
  5.     AppComponent,  
  6.     MyRedDirective  
  7.   ],  

OUTPUT

List of Directives in Angular 6

SUMMARY

  • Types of directives with examples.
  • Different ways to create an Angular 6 project using Angular CLI – Command Prompt and Visual Studio Code.