Showing posts with label angular 2 basics. Show all posts
Showing posts with label angular 2 basics. Show all posts

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 





Tuesday, 11 August 2015

A Deep dive into Angular 2 basics and difference between the versions tutorial

In this post we are going to see the new features present in the Angular 2, and the differences between the version 1.x and 2.0

First of all, i don't knew who is the person recommends the Angular 2 with, this kind of major changes, now currently angular 1.x versions are have a good popularity among the developers which is very easy to develop a single page applications. angular 1.x versions have many major advantages which makes that popular among the industry.

Features:
1. Two way binding
2. Routing
3. Change Detection
4. Directives
5. Services.
6. Controllers and the Scope concept.

Mainly the Two way binding makes the good feedback among the developers to develop the UI far better than any other framework. But recently google decide to soon release the angular 2 which have some major break changes in the framework.  Google and Microsoft are jointly working in the angular 2 framework,  angular 2 uses Typescript. 

Changes or features present in Angular 2

1 .No more Two way binding
      The major change is there is no more two way binding present in angular , all are uni directional, actually the thing which makes the angular popular among the industry in Two way binding ng-model, i.e is no more present in the up coming release. Angular team clearly indicates that unidirectional flow of data will be present in the angular 2., Here after there is no more $digest loop every time when ever a two way binding occurs.

2. New Router:
      The new release consists of a new router concepts.

3. No $scope
       Hereafter there is no concept called $scope , for a newbie to learn the concept of $scope is difficult, so to avoid the difficulties in learning they removed that concept

4. No Controller
       Angular 2 remove the concepts of controller , rather they uses the concept called web components where every component consists of View, component and class implementation.


@Component({
  selector: 'emp-view',
  componentServices: [
    emplist
  ]
})
@Template({
  url: './templates/emp-view.html',
  directives: [Foreach]
})
class EmpView{
  constructor() {
    this.employees = emplist.get();
  }
  addEmp(newemp) {
    this.employees.push(newemp);
  }

}

5. Fast change detection:
     Angular team changed the change detection mechanism for the newer version, new version refers many libraries implementation about change detection so angular team decided to give a optimized change detection.

6.Written in Typescript
   Angular 2 is written in Typescript , Typescript is statically typed language, so we can get the type errors in compile time itself , typescript is a superscript of ES6, ES6 is a superset of ES5. which are being transpiled to javascript

7 Virtual Dom concept 

8. Improved Dependency Injection

9. supporting mobile

But angular 2 doesnt have a backward compatibility support, so  many applications which are developed in version 1.x can use that if there is no performance issue, because if they want to change or migrate to version 2.0 then it is a huge cost for them, it is better to have a library which have more features than compact small performance increase.

from my concern google destroying the growth of  angular by giving a major change especially in removing of two way binding.

From this post you can see some of the changes takes place in the angular 2 version.