Tuesday 11 October 2016

Create a angular2 service and inject it in to Components

In this post we are going to see how to create a service in Angular2 application and inject it in to Component by Dependency injection. For this we are going to create a sample employee service  and inject it in to two components , for this we are going to create two components Employee and Student Component, But there is a issue in this if we are injecting service in to two components individually, then the new instance are created independently for this two service, so the data wont share or change wont reflect in other component



Creating a Service:

import { Injectable } from '@angular/core';

@Injectable()
export class DataService{

private data:string[]=["Rajesh","suresh","ramu"];

getEmployees(){
    return this.data;
}

addEmployee(name){
    this.data.push(name);
}

}





Inject Service independently in Component:

   In this we are injecting service in to the components using providers in there Component decorators directly, so what will happen his it will create a new instance , because of this each and every component will use the separate instance, nothing will be shared across the components

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
    selector:'employee',
    template:`
    <div style="display:inline-block;width:400px;vertical-align:top">
        <h1>Employee </h1>
        <div>
            <input type="text" #emp />
            <button (click)="addEmployee(emp.value)" 
                    class="btn btn-sm btn-primary">Add Emp</button>
            <button (click)="getEmployee()" 
                    class="btn btn-sm btn-primary">Get Employees</button>
            <div>
                <ul class="list-group">
                    <li class="panel list-group-item-primary" 
                        *ngFor="let e of employees" style="list-style:none;">
                        {{e}}
                    </li>
                </ul>
            </div>
        </div>
    </div>
    `,
    providers:[DataService]
})
export class EmployeeComponent
{
    employees:string[];

    constructor(private dataservice:DataService){
        
    }

    addEmployee(employeeName)
    {
        this.dataservice.addEmployee(employeeName);
    }

    getEmployee(){
        this.employees = this.dataservice.getEmployees();
    }
}


@Component({
    selector:'student',
    template:`
    <div style="display:inline-block;width:400px;vertical-align:top">
        <h1>Student </h1>
        <div>
            <input type="text" #std />
            <button (click)="addStudent(std.value)" 
                    class="btn btn-sm btn-primary">Add Student</button>
            <button (click)="getStudents()" 
                     class="btn btn-sm btn-primary">Get Students</button>
            <div>
                <ul class="list-group">
                    <li class="panel list-group-item-primary" 
                        *ngFor="let s of students" style="list-style:none;">
                        {{s}}
                    </li>
                </ul>
            </div>
        </div>
        </div>
    `,
    providers:[DataService]
})
export class StudentComponent
{
    students:string[];

    constructor(private dataservice:DataService){
        
    }

    addStudent(studentName)
    {
        this.dataservice.addEmployee(studentName);
    }

    getStudents(){
        this.students = this.dataservice.getEmployees();
    }
}




Module.ts:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { BaseRequestOptions, Http, Headers } from '@angular/http';
    import { webformComponent } from './Component/web.component'  
    import { EmployeeComponent,StudentComponent } from './employee.component'
    import { DataService } from './data.service';

    @NgModule({
        imports: [BrowserModule,FormsModule],
        exports: [],
        declarations: [webformComponent,EmployeeComponent,StudentComponent],       
        bootstrap:[webformComponent]
    })
    export class AppModule { 

    }


In module we can see the change in both the types

For ex:
In above Example we can see that the element add in the Employee doesn't reflect in Student


Output:

















Inject Service Globally for all component:

  In this we are injecting service in to the module using providers in module decorator directly, so what will happen his it will create a new instance , because of this each and every component will use the same instance, everything will be shared across the components

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
    selector:'employee',
    template:`
    <div style="display:inline-block;width:400px;vertical-align:top">
        <h1>Employee </h1>
        <div>
            <input type="text" #emp />
            <button (click)="addEmployee(emp.value)" 
                    class="btn btn-sm btn-primary">Add Emp</button>
            <button (click)="getEmployee()" 
                    class="btn btn-sm btn-primary">Get Employees</button>
            <div>
                <ul class="list-group">
                    <li class="panel list-group-item-primary" 
                        *ngFor="let e of employees" style="list-style:none;">
                        {{e}}
                    </li>
                </ul>
            </div>
        </div>
    </div>
    `
})
export class EmployeeComponent
{
    employees:string[];

    constructor(private dataservice:DataService){
        
    }

    addEmployee(employeeName)
    {
        this.dataservice.addEmployee(employeeName);
    }

    getEmployee(){
        this.employees = this.dataservice.getEmployees();
    }
}


@Component({
    selector:'student',
    template:`
    <div style="display:inline-block;width:400px;vertical-align:top">
        <h1>Student </h1>
        <div>
            <input type="text" #std />
            <button (click)="addStudent(std.value)" 
                    class="btn btn-sm btn-primary">Add Student</button>
            <button (click)="getStudents()" 
                     class="btn btn-sm btn-primary">Get Students</button>
            <div>
                <ul class="list-group">
                    <li class="panel list-group-item-primary" 
                        *ngFor="let s of students" style="list-style:none;">
                        {{s}}
                    </li>
                </ul>
            </div>
        </div>
        </div>
    `
})
export class StudentComponent
{
    students:string[];

    constructor(private dataservice:DataService){
        
    }

    addStudent(studentName)
    {
        this.dataservice.addEmployee(studentName);
    }

    getStudents(){
        this.students = this.dataservice.getEmployees();
    }
}





Module.ts:

In this we can see that the Providers is injected in to module directly to use it across the components.

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { BaseRequestOptions, Http, Headers } from '@angular/http';
    import { webformComponent } from './Component/web.component'  
    import { EmployeeComponent,StudentComponent } from './employee.component'
    import { DataService } from './data.service';

    @NgModule({
        imports: [BrowserModule,FormsModule],
        exports: [],
        declarations: [webformComponent,EmployeeComponent,StudentComponent],
        providers:[DataService],
        bootstrap:[webformComponent]
    })
    export class AppModule { 

    }


For ex:
In above Example we can see that the element add in the Employee reflect in Student



Output:









 







Main Component to Bootstrap:

import { Component,ViewEncapsulation,Input,Output } from '@angular/core';


@Component({
    selector:'webform',
    template:`
    <form>    
       <student></student> 
       <employee></employee>      
    </form>`,
    styles:[`
        
    .input{        
        border: 1px solid #ddd;
        -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.07);
        box-shadow: inset 0 1px 2px rgba(0,0,0,.07);
        background-color: #fff;
        color: #32373c;
        outline: 0;
        -webkit-transition: 50ms border-color ease-in-out;
        transition: 50ms border-color ease-in-out;
    }

    `],
    encapsulation:ViewEncapsulation.None
})
export class webformComponent{

    constructor(){

    }

}







index.html:

<body>
    <webform>Loading...</webform>
  </body>






From above post you learn how to inject the service in to the components in Angular2 applications

Saturday 8 October 2016

Set a style for an element in various ways using Angular2

In this post we are going to see how to set a style of an element in various ways using Angualr2



<div class="container">
    <br />

        Height : <input type="text" [(ngModel)]="height">
        Background : <input type="text" [(ngModel)]="background">
        Class : <input type="text" [(ngModel)]="classname">
        <button type="submit" [style.height.px]="height" 
                [style.background]="background" 
                [class]="classname"            
                >Submit</button>
    </div>


From the above code you can see that the height, background, class name of a button is dynamically changed using ngModel, this model value is bind to the element by [style.propertyname], for setting a pixel value we have to bind like [style.propertyname.px] , for class it should mention as [class]



Output:
**************








<br/>
    <div class="container">       
        Font Size :<label>{{fontsize}}</label>
        <input style="width:400px" type="range" [(ngModel)]="fontsize" />
        <br/>
        <button type="submit" class="btn btn-primary" 
          [ngStyle]="{'font-size':fontsize+'px'}">Dynamic Font Size</button>
    </div>


From the above code you can see the ngmodel value is bind to the element with the [ngStyle] directly

Output:
***************











<div class="container">
        <br/>
        <button type="submit" (click)="newstyle={'color':'red','background':'blue'}">
                Change Style</button>
        <button type="submit" (click)="newstyle={'height':'40px'}">
                Change Height</button>
        <button type="submit" (click)="newstyle={}">Remove Style</button> <br/><br/>        
        <input type="text" [ngStyle]="newstyle" />    
    </div>

From the above code you can see the style itself created and changed directly.

Output:
***************

















From this code you can learn how to change the style of an element in various ways using Angular2

Wednesday 5 October 2016

In this post we are going to see how to create a directive in Angular2 Js, for that we are taking a valid sample which are used in real time scenario like focus directive  which is used to focus an element based on the value of model value, when the model changes the value will be 

for basic setup and structuring of angular2 application please refer this link 
http://geeksmsdn.blogspot.in/2016/10/create-basic-structure-and-setup-for.html


After setup the basic structure here we are there to develop focused directive, what we are trying to do, we are trying to develop a directive like below.where we can changed the focus based on model value.








so now here we are going to develop the directive.  In the above two images we can see that the focus is changed from username to password.

import { Directive, ElementRef,Renderer,Input,AfterViewInit,
         HostListener,OnChanges,Output,EventEmitter } from '@angular/core';



@Directive({
    selector:'[focused]'    
})

export class FocusedDirective implements OnChanges , AfterViewInit{
    
    private istrigger = false;
    @Input('focused') isFocus:any;   
     @Output() focusedChange = new EventEmitter<any>(); 
    @Output() IsFocusChange = new EventEmitter();
    
    constructor(private ele:ElementRef,private render:Renderer){

    }

    @HostListener('blur',['$event.target'])
    onBlur(ele){      
        this.isFocus = false;  
        this.focusedChange.emit(this.isFocus);         
        this.IsFocusChange.next(this.isFocus);        
        this.istrigger = true;           
    }

    @HostListener('focus',['$event.target'])
    onFocus(ele){     
        if(!this.isFocus){
            this.focusedChange.emit(this.isFocus); 
            this.isFocus = true;  
            this.IsFocusChange.next(this.isFocus);         
        }
    }

    ngOnChanges(changes){
       if(this.isFocus){
            this.ele.nativeElement.focus();
            this.IsFocusChange.next(this.isFocus);
        }
        else{
            if(this.istrigger==false){
                this.ele.nativeElement.blur();
                this.IsFocusChange.next(this.isFocus);
                this.istrigger = true;
            }
            this.istrigger = false;
        }
    }
    
    ngAfterViewInit(){
        if(this.isFocus){
            this.ele.nativeElement.focus();            
        }
        else{
            this.ele.nativeElement.blur();           
        }
    }    

}

from above code you may wonder why this much of code , for a focus element, because we have handle all events changes through UI, Model, when you change the element focus that time also we are have to update the model sync with data

If you want only a update from Model to Directive then use the directive like as [directivename]="modelvalue", 
if you want a update from view to model and model to view in Two way binding then use like below [(directivename)]="modelvalue"

We are going to use above directive in our code , using the button click we are going to change the focus, and the same using mouse click on another element we can change the focus , this also update to model.



Now create a new component where we are going to use this directive name it as form.component,ts

import { Component, ViewEncapsulation } from '@angular/core';
    

    @Component({
        selector:'myform',
        templateUrl:'com/Forms/forms.html'
    })
    export class FormComponent{
        private userfocus:boolean;
        private passfocus:boolean;
        constructor(){
            this.userfocus = true;     
            this.passfocus = false;       
        }

        PasswordFocus(){
            this.userfocus=false;
            this.passfocus = true;            
        }

        UserNameFocus(){
            this.passfocus=false;
            this.userfocus=true;
        }

        focusChanged(value){
            console.log("focus is changed "+value);            
        }
    }



then create a forms.html to bind the template with the component.

<br/>
    <div class="container" style="width:400px">
        User Name : <input   [focused]="userfocus" type="text" 
                             class="form-control" 
                             placeholder="Please enter user name"  /> <br />
        Password  : <input [(focused)]="passfocus" 
                            (IsFocusChange)="focusChanged($event)" 
                            type="password" class="form-control" 
                            placeholder="Please enter password" /> <br/>
        <button type="submit" (click)="PasswordFocus()" 
                class="btn btn-lg btn-success btn-block">Password Focus</button>    
        <button type="submit" (click)="UserNameFocus()" 
                class="btn btn-lg btn-primary btn-block">Username Focus</button>
    </div>





,Now we are going to create a module using that we are bootstrap the component. 


app.module.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { FocusedDirective } from './directives/onload.directive';
    import { FormComponent } from './Forms/form.component';
    
    


    @NgModule({
        imports: [BrowserModule,FormsModule],
        exports: [],
        declarations: [FormComponent,FocusedDirective],
        bootstrap:[FormComponent]
    })
    export class AppModule { 

    }




main.ts

    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { AppModule } from './app.module';

    const platform = platformBrowserDynamic();

    let moduleref = platform.bootstrapModule(AppModule);

.

index.html

<body>
    <myform>Loading...</myform>
  </body>





Then now we are going to see the output
















from this post you can learn how to create a focused directive which can be change through model property.