Directives

  • A directive adds special behavior to basic html elements.
Attribute Directive
  • An attribute directive adds behavior using attributes to html elements.
Directive
 import {Component, Input, Directive} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 @Directive({  
  selector:'[my-hello]'  
 })  
 class MyHello {  
  constructor(){  
   console.log("Hello Directive");  
  }  
 }  
 /**  
  * Define the Component.  
  */  
 @Component({  
  selector: 'app',  
  directives:[MyHello],  
  templateUrl : 'templates/app.tpl.html',  
 })  
 class StarterTemplate {  
  private name: string;  
  private appId: string;  
  constructor () {  
   this.name = 'Starter Templates are here!!';  
   this.appId='This is the appId Value';  
  }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(StarterTemplate, []);  

Template
 <h1>{{ name }}</h1>  
 <h2 my-hello>Hello</h2>  

Host Property
  • The host property works on directive element object.
  • We can specify host properties for event handlers and to handle properties.
  • Here we are handling click event on the directive. 
  • We add attribute host to the directive definition.
  • Then we define a event as shown this event points to a method in the directive class which handles the event.
  • We can also attach properties.
    • For example we can specify Hidden property to host in directive definition which points to a variable.
    • Then we set the variable to true which will hide the element.
Component
 import {Component, Input, Directive, ElementRef, Renderer} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 @Directive({  
 selector:'[simple-directive]',  
 host:{  
  '(click)':'handleClick()',  
  '[hidden]':'isHidden'  
 }  
 })  
 class SimpleDirective {  
  @Input('aId') private appId: string;  
  private isHidden:boolean = false;  
  constructor(private elr: ElementRef, private renderer: Renderer){  
   elr.nativeElement.style.background= 'green';  
  }  
  handleClick(){  
   console.log("I was clicked");  
  }  
  public ngAfterViewInit() {  
   this.renderer.setElementProperty(this.elr.nativeElement,'innerHTML',this.appId);  
  }  
 }  
 /**  
  * Define the Component.  
  */  
 @Component({  
  selector: 'app',  
  directives:[SimpleDirective],  
  templateUrl : 'templates/app.tpl.html',  
 })  
 class HostComponent {  
  private name: string;  
  private appId: string;  
  constructor () {  
   this.name = 'Directive Host';  
   this.appId='This is the appId Value';  
  }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(HostComponent, []);  
Template
 <h1>{{ name }}</h1>  
 <div simple-directive [aId]="name"></div>  

ngIf directive
  • ngIf is a structural directive
  • We use a star(*ngIf) i.e. before ngIf which indicates that there is a template behind the directive.
    • Angular creates a template and wraps the whole thing in a template directive.
  • ngIf binds to a data which is read as a boolean value.
    • We can directly bind as *ngIf="false" or *ngIf="true" which treats these as values.
    • "[]" represents an empty range and is a true value.
    • "''" represents an empty string and is a false value.
  • If the value is true component is shown else component is not shown.
Component
 import {Component, Input} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 /**  
  * Define the Component.  
  */  
 @Component({  
  selector: 'app',  
  templateUrl : 'templates/app.tpl.html',  
 })  
 class StarterTemplate {  
  private name: string;  
  private isReady:boolean;  
  constructor () {  
   this.name = 'ngIf Example';  
   this.isReady=false;  
  }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(StarterTemplate, []);  
View
 <h1>{{ name }}</h1>  
 <div *ngIf="isReady" >The quick brown fox jumps over the lazy dog</div>  

ngFor Directive/ngRepeat Directive
  • ngFor is equivalent to ngRepeat in angular 1.
  • ngRepeat directive was very helpful in creating tables.
  • Allows us to loop through an array and showresult on a page as shown.
  • The array can be an array of objects or numbers as shown.
  • We can also populate a table and rows and headers from an array of objects as shown.
main.ts
 import {Component, Input} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 /**  
  * Define the Component.  
  */  
 @Component({  
  selector: 'app',  
  templateUrl : 'templates/app.tpl.html',  
 })  
 class StarterTemplate {  
  private name: string;  
  private nums: number[];  
  private users: any[];  
  private headers: any[];  
  constructor () {  
   this.name = 'ngFor Directive';  
   this.nums = [1,2,3,4];  
   this.users=[  
    {name: 'Tom', id:'1', isActive:false},  
    {name: 'Kim', id:'2', isActive:true},  
    {name: 'John', id:'3', isActive:false}  
   ]  
   this.headers= Object.keys(this.users[0]);  
  }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(StarterTemplate, []);  
app.tpl.html
 <h1>{{ name }}</h1>  
 <ul>  
   <li *ngFor="let num of nums" >{{num}}</li>  
 </ul>  
 <ul>  
   <li *ngFor="let user of users" >{{user.name}}, {{user.id}}, {{user.isActive ? 'Active' : 'Inactive'}}</li>  
 </ul>  
 <table>  
   <thead>  
   <tr>  
     <th *ngFor="let header of headers" >{{header}}</th>  
   </tr>  
   </thead>  
   <tbody>  
     <tr *ngFor="let user of users" >  
       <td>{{user.name}}</td>  
       <td>{{user.id}}</td>  
       <td>{{user.isActive ? 'Active' : 'Inactive'}}</td>  
     </tr>  
   </tbody>  
 </table>  

ngClass Directive
  • Used to add classes to Html elements which can be controlled from typescript code.
main.ts
 import {Component, Input} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 /**  
  * Define the Component.  
  */  
 @Component({  
  selector: 'app',  
  templateUrl : 'templates/app.tpl.html',  
 })  
 class StarterTemplate {  
  private name: string;  
  private appId: string;  
  private titleClasses:any;  
  constructor () {  
   this.name = 'NG Class Example';  
   this.appId='This is the appId Value';  
   this.titleClasses = {  
    isActive: false,  
    another: true  
   }  
 }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(StarterTemplate, []);  
app.tpl.html
 <h1>{{ name }}</h1>  
 <h1 class="title" [ngClass]="titleClasses">Title</h1>  
 <h1 class="title" [ngClass]="{isActive: true}">Inline</h1>  
ngStyle Directive
  • We can style elements in our HTML attached to our component.
  • We add this directive in the element whose value can either be an object or inline values with object.
    • In line values are preferred over object values.
main.ts
 import {Component, Input} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 /**  
  * Define the Component.  
  */  
 @Component({  
  selector: 'app',  
  templateUrl : 'templates/app.tpl.html',  
 })  
 class StarterTemplate {  
  private name: string;  
  private appId: string;  
  private cmpStyle: object;  
  private fontSize: string;  
  private cmpColor: string;  
  constructor () {  
   this.name = 'ngStyle';  
   this.appId='This is the appId Value';  
   this.fontSize='20px';  
   this.cmpColor='blue';  
   this.cmpStyle={  
    'font-size': this.fontSize  
   }  
  }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(StarterTemplate, []);  
app.tpl.html
 <h1>{{ name }}</h1>  
 <p [ngStyle]="cmpStyle">The quick brown fox jumped over the lazy dog</p>  
 <p [ngStyle]="{'color': cmpColor}">Inline</p>  

ngSwitch Directive
  • We can decide which part of html we want to show based on some condition.
  • We use the ng-switch based on values passed from component to decide and show particular html.
  • When no value matches ngSwitch Default is triggered as follows.
main.ts
 import {Component, Input} from 'angular2/core';  
 import {bootstrap} from 'angular2/platform/browser';  
 /**  
  * Define the Component.  
  */  
 @Component({  
  selector: 'app',  
  templateUrl : 'templates/app.tpl.html',  
 })  
 class StarterTemplate {  
  private name: string;  
  private appId: string;  
  private status: string;  
  constructor () {  
   this.name = 'Starter Templates are here!!';  
   this.appId='This is the appId Value';  
   this.status='success';  
  }  
 }  
 /**  
  * Bootstrap the app with `StarterTemplate`.  
  */  
 bootstrap(StarterTemplate, []);  
app.tpl.html
 <h1>{{ name }}</h1>  
 <div [ngSwitch]="status">  
   <template [ngSwitchWhen]="'error'">Error Message</template>  
   <template [ngSwitchWhen]="'success'">Done</template>  
   <template [ngSwitchWhen]="'progress'">In Progress</template>  
   <template ngSwitchDefault>Unknown</template>  
 </div>  

ngOptions Directive
  • To create a dropdown list based on an object or an array in Angular Js we should use ng-options directive 

No comments:

Post a Comment