Angular Directives With Examples

What is Directive? 

  • Directives play an important role in Angular 2 projects, when we displaying the templates or html pages in our project. By using this we can easily manipulate our Dom layout.
  • In Angular 2, there are three types of directives those are component directive, attribute directive and structural directive

Classification of Directives
Angular 2 Directives

What is Component directive? 

  • Component directive, is nothing but a simple class which is decorated with the @component decorator.
  • In Angular 2 ,Normal typescript class will become a Component class once it has been decorated with @component decorator
  • It is mainly used to specify the html templates.
  • It is most commonly used directive in angular project
  • If you need more info on angular component, then kindly refer here: need to add

Built In Component Directive @component 

@component decorator provides additional metadata that determines how the component should be processed, instantiated and used at runtime

Simple Example

@component 

File name app.component.ts

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

File name index.html

  1. <!DOCTYPE html>  
  2. <html>  
  3.   <head>  
  4.     <title>Angular QuickStart</title>  
  5.     <base href="/src/">  
  6.     <meta charset="UTF-8">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.     <link rel="stylesheet" href="styles.css">  
  9.   
  10.     <!-- Polyfill(s) for older browsers -->  
  11.     <script src="/node_modules/core-js/client/shim.min.js"></script>  
  12.   
  13.     <script src="/node_modules/zone.js/dist/zone.js"></script>  
  14.     <script src="/node_modules/systemjs/dist/system.src.js"></script>  
  15.   
  16.     <script src="systemjs.config.js"></script>  
  17.     <script>  
  18.       System.import('main.js').catch(function(err){ console.error(err); });  
  19.     </script>  
  20.   </head>  
  21.   
  22.   <body>  
  23.   
  24.     <!--Here is the selector mapped-->  
  25.     <my-app>Loading AppComponent content here ...</my-app>  
  26.   
  27.   
  28.   
  29.   </body>  
  30. </html>  

Output

 Angular 2 Directives
What is attribute directive?

  • It is mainly used to change/modify the behavior of the html element.
  • As the name tells, it is used to change the attributes of the existing html element. In Angular 2 there are many built in attribute directives. Some of the useful ones are NgClass, NgStyle 

Built-In Attribute Directive: NgStyle, NgClass

NgStyle

NgStyle directive is similar to one of data binding technique called style binding in angular, but the main difference is, NgStyle used to set multiple inline styles for html element.

NgClass

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

Simple Example

NgStyle

File Name app.component.ts

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.     template: ` <button style='color:blue' [ngStyle]="ApplyStyles()">Style Applied</button>  
  6.                     `  
  7. })  
  8. export class AppComponent {  
  9.     isBold: boolean = true;  
  10.     fontSize: number = 30;  
  11.     isItalic: boolean = true;  
  12.   
  13.     ApplyStyles() {  
  14.         let styles = {  
  15.             'font-weight'this.isBold ? 'bold' : 'normal',  
  16.             'font-style'this.isItalic ? 'italic' : 'normal',  
  17.             'font-size.px'this.fontSize  
  18.         };  
  19.   
  20.         return styles;  
  21.     }  
  22. }  

Output

Angular 2 Directives 
Simple Example

NgClass

File Name app.component.ts 

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

Output

Angular 2 Directives

What is Structural Directive?
  • Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.
  • To say in simple words, unlike Attribute Directive which we see above, 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.
  • Structural directives are easy to recognize by using an asterisk (*)

Built-in structural directive - NgIf, NgFor, and NgSwitch 

  • NgIf is used to create or remove a part of DOM tree depending on a condition.
  • NgFor is used to customize data display. It is mainly used for display a list of items using repetitive loops
  • NgSwitch 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.

Simple Example

NgIf

Angular 2 Directives

Output

Angular 2 Directives
Negative If ngif= false then it won’t show the output, you will see the

Angular 2 Directives

Output

Angular 2 Directives
Example

NgFor

FileName app.component.ts 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.     templateUrl: 'app/app.component.html',    
  6. })  
  7. export class AppComponent {  
  8.     employees: any[] = [  
  9.         {  
  10.             code: 'emp1', name: 'Karthik', gender: 'Male',  
  11.             annualSalary: 5500, dateOfBirth: '25/6/1988'  
  12.         },  
  13.         {  
  14.             code: 'emp2', name: 'sachin', gender: 'Male',  
  15.             annualSalary: 5700.95, dateOfBirth: '9/6/1982'  
  16.         },  
  17.         {  
  18.             code: 'emp3', name: 'rahul', gender: 'Male',  
  19.             annualSalary: 5900, dateOfBirth: '12/8/1979'  
  20.         },  
  21.         {  
  22.             code: 'emp4', name: 'Mary', gender: 'Female',  
  23.             annualSalary: 6500.826, dateOfBirth: '14/10/1980'  
  24.         },  
  25.     ];  
  26. }  

FileName app.component.html 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6. </head>  
  7. <body>  
  8.     <table>  
  9.         <thead>  
  10.             <tr>  
  11.                 <th>Code</th>  
  12.                 <th>Name</th>  
  13.                 <th>Gender</th>  
  14.                 <th>Annual Salary</th>  
  15.                 <th>Date of Birth</th>  
  16.             </tr>  
  17.         </thead>  
  18.         <tbody>  
  19.             <tr *ngFor='let employee of employees'>  
  20.                 <td>{{employee.code}}</td>  
  21.                 <td>{{employee.name}}</td>  
  22.                 <td>{{employee.gender}}</td>  
  23.                 <td>{{employee.annualSalary}}</td>  
  24.                 <td>{{employee.dateOfBirth}}</td>  
  25.             </tr>  
  26.             <tr *ngIf="!employees || employees.length==0">  
  27.                 <td colspan="5">  
  28.                     No employees to display  
  29.                 </td>  
  30.             </tr>  
  31.         </tbody>  
  32.     </table>  
  33. </body>  
  34. </html>  

Output

Angular 2 Directives

Example

NgSwitch

File Name app.component.ts 

  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.     template: `<h2>{{title}}</h2>    
  6. <p *ngIf="showElement">Show Element</p>    
  7. <div [ngSwitch]="inpvalue">    
  8. <p *ngSwitchCase="1">You selected Monday</p>    
  9. <p *ngSwitchCase="2">You selected Tuesday</p>    
  10. <p *ngSwitchCase="3">You selected Wednesday</p>   
  11. <p *ngSwitchDefault>Sorry Invalid selection!!</p>    
  12. </div>`    
  13. })  
  14. export class AppComponent {  
  15.   
  16.     inpvalue: number = 3;  
  17. }  

Output

Angular 2 Directives
Additional Note about @Directive

IF we want create a custom attribute, then we can mark a normal class as an Angular 2 directive with the help of a @Directive decorator.

Difference between Component, Attribute and Structural Directives? 

ComponentAttribute  DirectiveStructural Directives
Component directive is used to specify the template/html  for the Dom LayoutAttribute directive is used to change/modify the behaviour of the html element in the Dom LayoutStructural directive used to add or remove the html Element in the Dom Layout,
Built in

@component
Built in

NgStyle, NgClass
Built in

*NgIf,*NgFor,*NgSwitch

Conclusion

In Angular 2, using the advantages of directives we can implement many things in our project easily. Hope the above was useful, kindly let me know your thoughts or feedback.

Up Next
    Ebook Download
    View all
    Learn
    View all