What is Directive?

Classification of Directives
Angular 2 Directives

What is Component directive?

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. //decorator
  3. @Component({
  4. selector: 'my-App',
  5. template: '<h1>{{name}}</h1>'
  6. })
  7. export class AppComponent {
  8. name: string = "Angular 2"
  9. }

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. <!-- Polyfill(s) for older browsers -->
  10. <script src="/node_modules/core-js/client/shim.min.js"></script>
  11. <script src="/node_modules/zone.js/dist/zone.js"></script>
  12. <script src="/node_modules/systemjs/dist/system.src.js"></script>
  13. <script src="systemjs.config.js"></script>
  14. <script>
  15. System.import('main.js').catch(function(err){ console.error(err); });
  16. </script>
  17. </head>
  18. <body>
  19. <!--Here is the selector mapped-->
  20. <my-app>Loading AppComponent content here ...</my-app>
  21. </body>
  22. </html>

Output

Angular 2 Directives
What is attribute directive?

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

Output

Angular 2 Directives
Simple Example

NgClass

File Name app.component.ts

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

Output

Angular 2 Directives

What is Structural Directive?

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

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

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

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.