Friday 28 October 2016

How to set the relative url for the template of Angular2 Component

In this post we are going to see how to set the relative url for the template of angular2 component. First we have to understand the concepts of loading templates in Angular2 Component.Normally when you see the component if you have the TemplateUrl where we will specify the path  which will starts from the path what we specified in the system.config.js, for Example in below example we can see the for a star rating component we have html which is also in the same directory but it is specified from the root path.




From the above example you can see the output of that configuration.





Star Rating Component is a reusable component, here we have one issue, whenever we are adding this another project we have to configure it in the same path because it is specified from the root, so what we can do is,  we change the path to relative path ,relative to component location.







Now we got one issue, template is not loaded because it is mapped related to the root server path,








Now how we can fix this issue,we have to tell the component to have moduleId, which will help the component to load the template with relative to the component location.





Now see the output:







From this post you can see how to load the template in Angular2 component with relative path.


Tuesday 25 October 2016

Create a Angular2 Print Component which will print the user defined HTML element in DOM using Typescript (Print component)

In this post we are going to see how to create a Print component which will print the user defined element in DOM using the Typescript, for this first we have to create a Print component then we have to use that component in another component, later we will get a print button in the screen, then when we click the print button, we can find the print of that particular area in the printer.






Component:


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

@Component({
    selector:'print-page',
    encapsulation:ViewEncapsulation.None,
    template:`
     <button (click)="printDiv()" 
        class="btn btn-sm btn-primary">Print</button>
     <div id="printpage">
     </div>
    `,
    styles:[`
    @media screen {
        #printpage, #printpage * {
            display:none;
        }
    }
      @media print {
          body *{
              visibility:hidden;
              background: transparent;
            -webkit-print-color-adjust: exact !important; 
          }
          
          #printpage, #printpage *{
              visibility:visible;
               -webkit-print-color-adjust: exact !important; 
                box-shadow: inset 0 0 0 1000px gold;
          }

          #printpage{
            position:absolute;
            left:0;
            top:0;             
          }
      }
    `]

})
export class PrintComponent implements OnChanges{
    
    @Input('section') section:string;
    @Output() sectionChange = new EventEmitter<any>(); 

    constructor(private ele:ElementRef){
        if(this.section===undefined)
            this.section = '';
    }

    ngOnChanges(changes){
        if(changes.section && changes.section.currentValue!==undefined
        && changes.section.currentValue!==''){
           
        }
    }

    afterPrint(){
        console.log("after print");
        this.ele.nativeElement.children[0].innerHTML = '';
        this.sectionChange.emit(''); 
        this.section = '';
        
    }
 

    printDiv() {

        if(this.section && this.section != undefined && this.section!='') {
            var printContents = document.getElementById(this.section).innerHTML;
            var originalContents = document.body.innerHTML;      

        if(window){
            if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
                var popup = window.open('', '_blank', 
                'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,'
                +'location=no,status=no,titlebar=no');
               
                popup.window.focus();
                popup.document.write('<!DOCTYPE html><html><head>  '
        +'<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css" '
        +'media="screen,print">'
        +'<link rel="stylesheet" href="style.css" media="screen,print">'             
        +    '</head><body onload="window.print()"><div class="reward-body">' 
        + printContents + '</div></html>');
                popup.onbeforeunload = function (event) {           
                    popup.close();          
                    return '.\n';
                };
                popup.onabort = function (event) {             
                    popup.document.close();           
                    popup.close();         
                }
            } else {
                var popup = window.open('', '_blank', 'width=800,height=600');
                popup.document.open();
                popup.document.write('<html><head>'+
        +'<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css"'
        +' media="all">'
        +'<link rel="stylesheet" href="style.css" media="all">'                
        +'</head><body onload="window.print()">' + printContents + '</html>');
                popup.document.close();
            }

             popup.document.close();
            }
            return true;
        }
    }

fetchStylesheets(){
     var output:string= '';
     for(var i=0;i<document.styleSheets.length;i++){
       output = output +' <link rel="stylesheet" type="text/css" href="'+    
                window.document.styleSheets[0].href +'" /> ';
     }
     return output;
 }

 fetchscriptSheets(){
     var output:string= '';
     for(var i=0;i<document.scripts.length;i++){
       output = output +' <script type="text/javascript" src="'+    
                window.document.scripts[0].src +'" /> ';
     }
     return output;
 }
   
}




In the above component you may notice one things i am created a two methods fetch the stylesheets , scripts, but i didnt use it, if you want to use in the output to load the scripts in printing then you can added that in the execution .


using the print component in another employee component:, for more detail reference about the employee component 
please refer previous post. for service and model data



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

@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 style="margin-top:20px">
            <ul class="list-group" style="display:-webkit-box;overflow-x:scroll">
                <li class="panel list-group-item-primary" 
                *ngFor="let e of employees" style="list-style:none;">
                <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">{{e.username}}</h3>
                </div>
                <div class=""panel-body>
                    <div class="text-info" style="padding:5px;">{{e.name}} 
                    <span class="btn btn-sm btn-primary" 
                        (click)="getAlbum(e.id)">Get Album</span></div>
                    <div class="text-primary" style="padding:5px;"> 
                        {{e.address.city}},{{e.address.zipcode}}</div>
                    <div *ngIf="e.albums">
                    <ul class="list-group">
                    <li class="list-group-item" *ngFor="let alb of e.albums">
                        <div class="panel panel-default">
                            <div class="panel-heading">{{alb.title}}</div>
                            <div class=""panel-body>                       
                                <img [src]="alb.thumbnailUrl" />
                            </div>
                        </div>
                    </li>
                    </ul>
                    </div>
                </div>
                </div>
                </li>
            </ul>
            </div>
        </div>
    </div>
    `   
})
export class EmployeeComponent
{
    employees:IUser[];
  
    constructor(private dataservice:DataService){
        
    }

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

    getEmployee(){
        this.dataservice.getEmployees()
        .subscribe(
            customer=>this.employees=customer,
            error=>console.log("error"+error)
            );
       
    }

    getAlbum(id){
        this.dataservice.getAlbums(id)
        .subscribe(
            albums=>this.employees.find(emp=>emp.id==id).albums = albums
            );
    }
}


When user click on the get album, it will fetch information about the particular user id's album , then click print button 

Output:


















After click the print button , the view of the print screen















From this post you can learn how to create a print component in the angular2 using the Typescript which will print the user defined element in the DOM 





Create a Angular2 service and send a HTTP Request using Typescript

In this post we are going to see how to make an http request from inside the angular2 service, For this first we have to inject the HTTP in the service layer using dependency injection. we are using the Observable API for catch the response of HTTP request. Observable is a Lazy API

























First we have to create a interface based on the data response , then we have to create a service which will invoke the Http call.


export interface IUser{
    id:number;
    name:string;
    username:string;
    email:string;
    address:IAddress;
    phone:string;
    website:string;
    company:ICompany;
    albums:IAlbum[];    
}

export interface ICompany{
    name:string;
    catchPharse:string;
    bs:string;
}

export interface IAddress{
    street:string;
    suite:string;
    city:string;
    zipcode:string;
    geo:IGeo;
}

export interface IGeo{
    lat:string;
    lon:string;
}

export interface IAlbum{
    albumId:number;
    id:number;
    title:string;
    url:string;
    thumbnailUrl:string;
}

then we have to create a service with HTTP as a dependency, the instance of the HTTP will be passed in constructor.



    import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';
    import { Observable } from 'rxjs/observable';
    import { IUser,IAlbum } from './user';
    import 'rxjs/add/operator/catch'
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/do';

    @Injectable()
    export class DataService{

    private data:string[]=["Rajesh","suresh","ramu"];
    private url:string = "http://jsonplaceholder.typicode.com/users";

    constructor(private _http:Http){

    }

    getEmployees(): Observable<IUser[]>{
    return this._http.get(this.url)
    .map((response:Response)=><IUser[]>response.json())
    .do(data=>console.log("All : "+JSON.stringify(data)))
    .catch(this.HandleError);
    }

    getAlbums(id):Observable<any>{

    return this._http.get("http://jsonplaceholder.typicode.com/photos?albumId="+id)
    .map((response:Response)=><IAlbum[]>response.json())
    .do(data=>console.log("album "+JSON.stringify(data)))
    .catch(this.HandleError);       

    }


    private HandleError(error:Response){
        console.log(error);
        return Observable.throw(error.json().error || "server error");
    }

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

    }



Next we have to invoke the call from inside the component , here we have to subscribe the request because return type of the method is a observable of particular type, in observable to get the response we have to subscribe , in subscribe we have three parameter, success, error, complete.



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

@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 style="margin-top:20px">
            <ul class="list-group" style="display:-webkit-box;overflow-x:scroll">
                <li class="panel list-group-item-primary" 
                *ngFor="let e of employees" style="list-style:none;">
                <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">{{e.username}}</h3>
                </div>
                <div class=""panel-body>
                    <div class="text-info" style="padding:5px;">{{e.name}} 
                    <span class="btn btn-sm btn-primary" 
                        (click)="getAlbum(e.id)">Get Album</span></div>
                    <div class="text-primary" style="padding:5px;"> 
                        {{e.address.city}},{{e.address.zipcode}}</div>
                    <div *ngIf="e.albums">
                    <ul class="list-group">
                    <li class="list-group-item" *ngFor="let alb of e.albums">
                        <div class="panel panel-default">
                            <div class="panel-heading">{{alb.title}}</div>
                            <div class=""panel-body>                       
                                <img [src]="alb.thumbnailUrl" />
                            </div>
                        </div>
                    </li>
                    </ul>
                    </div>
                </div>
                </div>
                </li>
            </ul>
            </div>
        </div>
    </div>
    `   
})
export class EmployeeComponent
{
    employees:IUser[];
  
    constructor(private dataservice:DataService){
        
    }

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

    getEmployee(){
        this.dataservice.getEmployees()
        .subscribe(
            customer=>this.employees=customer,
            error=>console.log("error"+error)
            );
       
    }

    getAlbum(id){
        this.dataservice.getAlbums(id)
        .subscribe(
            albums=>this.employees.find(emp=>emp.id==id).albums = albums
            );
    }
}



Next thing we have to inject the module in to root module then start the app to run



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

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

    }




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

    const platform = platformBrowserDynamic();

    let moduleref = platform.bootstrapModule(AppModule);



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










When you click on the Get Employees, it will fetch the information














When user click on the Get Album for each user this will fetch the album info










From this post you can learn how to invoke a Http call from the angular2 service