Showing posts with label Bootstrap. Show all posts
Showing posts with label Bootstrap. Show all posts

Saturday, 1 October 2016

Create a Star Rating Component in Angular2 JS using Typescript

In this post we are going to see how to create a component in Angular2 Js, for that we are taking the a valid sample component which are used in real time scenario like star rating component which is used to rate a value in applications

for basic setup and structuring of angular2 application please refer this link https://angular2js.blogspot.in/2016/10/create-basic-structure-and-setup-for.html, After setup the basic structure here we are there to develop a star rating component, what we are trying to do, we are trying to develop a component like below.




 Rating control:
***********************



To do this first we have to create a component and then module , finally we have to import that module that't it

Steps to do:
*****************************************
1. Create a folder name editors under the com folder
2. Create a file named star.ts
3. Create a file named ratingcontrol.ts
4. Create a file named ratingcontrol.html
5. Create a file named editor.module.ts
6. Import this module
7. add the Star Component in the App.component
7. Bootstrap the App.Module



Star.ts

From this Code you may see what we are trying to do, we are creating a model for star component, based on which we are controlling the star rating component 

export class star {
    public filled:boolean;
}




ratingcontrol.ts

From this code you can see the full implementation of star rating component, where are trying to build a component like below, here we are declaring component in three kind of formats with simple implementation , in one tag we are passing value directly to the property, in another thing we are passing value to the control with the models, 

if you want to pass a value directly then pass it like         color="red"
if you want to pass a value from model then pass it like  [color]="color"
if you want to pass a model with two way then                  [(color)] ="color"

The star component have the following properties

ratingvalue : This is the actual value which represents the value of rating,This can acts as one-way and well as Two way 

max : This is the number representation of total number of stars to draw

color : This is the color of the Outline of the star

readonly: This property makes the component readonly, i.e user cant give rating, but in code you can change it

fillcolor  : This property is the color of the star, if you doesnt give this then gold is default color

OnRatingChanged : This is the callback event which can trigger when rating is changed ,this can be hooked in your applications , to get the notify when changes


<star-rating    [(ratingvalue)]="rating"  [max]="max" 
                [color]="starcolor"       [readonly]="readonly" 
                [fillcolor]="fillcolor"   (OnRatingChanged)="ratingChanged($event)" >
 </star-rating>


<star-rating    ratingvalue="4"     max="10" 
                color="gray"        fillcolor="orange" 
                readonly="false"    (OnRatingChanged)="ratingChanged($event)" >
</star-rating>

 <star-rating    ratingvalue="2"   max="5" color="green" fillcolor="green">
 </star-rating>

   import {    Component,ViewEncapsulation,Input,Output,
                    EventEmitter,ElementRef,OnInit,OnChanges,
                    DoCheck,Renderer,AfterViewInit,AfterViewChecked,
                    AfterContentInit,ViewChildren,ContentChildren,
                    ChangeDetectionStrategy, HostBinding 
                } from '@angular/core';

   import { star } from './star';

    @Component({
        selector:'star-rating',
        changeDetection:ChangeDetectionStrategy.OnPush,
        templateUrl:'com/editors/ratingcontrol.html',
        styles:[`

            .rating {
                unicode-bidi: bidi-override;              
                text-align: start; 
                display:inline-block;  
                direction:rtl;      
            }    
            .star{      
                color: gold;    
            }
            .rating > span {
                display: inline-block;
                position: relative;
                width: 0.9em;
                font-size:30px;
            }
            .rating:hover{
                cursor:pointer;
            }
            .rating > span:hover,
            .rating > span:hover ~ span {
                color: transparent;
            }
        .rating > span:hover:before,
        .rating > span:hover ~ span:before {
                content: "\\2605";
                position: absolute;
                left: 0;
                color: gold;
        }

        `],

        host:{    
        }

     })



   export class StarRatingComponent implements OnInit , 
                                                    OnChanges,
                                                    AfterViewInit,
                                                    AfterContentInit,
                                                    AfterViewChecked {

        @Input() ratingvalue:number;
        @Output() ratingvalueChange:EventEmitter<number> = new EventEmitter<number>();

        @Output() OnRatingChanged = new EventEmitter();

        @Input() max:number;

        @Input() readonly:boolean;

        @Input() starsize:number;

        @Input() color:string;

        @Input() fillcolor:string;

        @Output() OnMouseOver = new EventEmitter();

        @ViewChildren('starfilled') starChildren;

        public stars:star[];
        private ele:ElementRef;
        private render:Renderer;
        private changeElements:HTMLElement[]

        constructor(e1:ElementRef,render:Renderer){
            this.ele = e1;
            this.render = render;  
            this.fillcolor = "gold";    
        }

        public ngOnInit(){
        
        }

        public ngOnChanges(){ 
        if(this.readonly==undefined){
            this.readonly = false;
        }     
        if(typeof(this.readonly)=="string"){    
            this.readonly = (String(this.readonly)=="true");    
        }
        this.updateStars();
        }

        public ngAfterViewInit(){
        this.starChildren.changes.subscribe(changes=>
        {   
            this.changeElements = changes._results.map(
                (eleref)=> eleref.nativeElement
                );

            this.OnRatingChanged.next(
                {  ratingvalue:this.ratingvalue,
                    max:this.max,
                    Changedelements:this.changeElements
                });           
        });  
        }

        public OnMouseenter(evt){  
        this.OnMouseOver.next(evt);
        }

        public ngAfterViewChecked(){
            
        }

        public ngAfterContentInit(){
        
        }

        private updateStars(){
            this.stars = [];    
            var j = this.max - this.ratingvalue;

            for (var i = 1; i <= this.max; i++) {                                  
                    this.stars.push({ filled: i > j });         
                }
            this.render.setElementStyle(this.ele.nativeElement,'color',this.color);
        }

        private toggle(index){     
            if(this.readonly===false){
            this.ratingvalue =  (this.max - index);
            this.updateStars(); 
            this.ratingvalueChange.emit(this.ratingvalue);      
            }
        }


    }





ratingcontrol.html

From this you can see that the implementation of star component. create this html file and link it with component

<div class="rating">
    <span   *ngFor="let star of stars; let i=index" 
            [class.star]="star.filled" 
            (click)="toggle(i)">
        <span   #starfilled (mouseenter)="OnMouseenter($event)" 
                [style.color]="fillcolor" *ngIf="star.filled">
                    &#9733;
        </span>
        <span   (mouseenter)="OnMouseenter($event)" 
                *ngIf="!star.filled">
                    &#9734;
        </span>        
    </span>
</div>






editor.module.ts

From this code , you can see that the implementation of module for our star rating component

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { StarRatingComponent } from './ratingcontrol';

@NgModule({
    imports:[CommonModule],
    declarations:[StarRatingComponent],
    providers:[],
    exports:[StarRatingComponent]
})
export class EditorModule{

}





app.component.ts
After creating the module , we have to create a root component in which we are adding the star component,In this component we can see the implementation of star component in three different ways 

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

  @Component({
    selector:'my-app',
    template:`
    <span style="font-size:18px;">Rajesh G an Architect :</span>  
    <star-rating    ratingvalue="4"     max="10" 
                    color="gray"        fillcolor="orange" 
                    readonly="false"    (OnRatingChanged)="ratingChanged($event)" >
    </star-rating>

    <br/>
    <span style="font-size:18px;">Tamil Movie rate it :</span>
    <star-rating    [(ratingvalue)]="rating"  [max]="max" 
                    [color]="starcolor"     [readonly]="readonly" 
                    [fillcolor]="fillcolor" (OnRatingChanged)="ratingChanged($event)" >
    </star-rating>

    <br/>
     <span style="font-size:18px;">Indian Cricket Team :</span>
    <star-rating    [(ratingvalue)]="rating2"   max="5" color="blue" fillcolor="blue">
    </star-rating>

    <br/>
     <span style="font-size:18px;">Microsoft Bug :</span>
    <star-rating    ratingvalue="2"   max="5" color="green" fillcolor="green">
    </star-rating>

    <div>
    <button type="button" class="btn btn-sm btn-success" (click)="PrintValue()">
        Print Values
    </button>
    </div>

    `,    
    encapsulation:ViewEncapsulation.None ,
    styles:[]  ,     
  })


  export class AppComponent{

    rating = 3;
    rating2 = 2;

    max = 5;
    starcolor="red";
    readonly = false;
    fillcolor="red";

    ratingChanged(value){
        console.log("OnRating change Callback");
        console.log(this.rating);
        console.log(value);
        console.log("");
    }

    PrintValue(){    
        console.log("Values of Ratings");
        console.log("Rating :" + this.rating);
        console.log("Rating1 :"+this.rating2);
        console.log("");
    }

  }





app.module.ts

From this code you can see the root component is bootstrapped and dependencies are injected

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';
    import { EditorModule  } from './editors/editor.module';
    import { AppComponent } from './app.component';


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

    }




main.ts

Here we are bootstrapping the 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);




index.html

Here in the index.html file we can see the my-app tag, which will trigger the app.component

<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="style.css">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
      
    <script src="lib/jquery.js"></script>
    <script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
  

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    
    <script>
      System.import('com').catch(function(err){ 
          console.error(err); 
        });
    </script>

  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>





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







Output of a callback function where we are printing the values of rating control , when rating changes, in this function we can notice that the model also updated when we change the value, this is because of two way binding 












Callback console print values when value changes in the star rating component











From this post you can learn how to create a star rating component using Angular 2 and Typescript, and also you can learn how to inject that component in to the root module.





Create a Basic structure and setup for developing a Angular2 js application using Typescript with an example

In this post we are going to see the basic structure and setup for developing a angular2 single page application using Typescript, In angular2 lot of release are released by angular team, each and every release had lot of break through changes, even in the last release it have many changes from the Previous one, so we cant say which is correct way of development, each and every versions have different things in coding and setup. 


Now let we see what is the basic structure needed for develop a Angular 2 applications, in this sample we will use the Typescript for development. and we will create a Hello world sample.

First we will configure the basic things needed for project like configs.

Step 1. Setup the package.json
Step 2. Setup the tsconfig.json
Step 3. Setup the typings.json
Step 4. Create the systemjs.config.js
Step 5. Create the main.ts typescript file
Step 6. Run the npm
Step 7. Add the index.html file
Step 8. Create a component
Step 9. Create and Bootstrap a module
Step 10. Add the component in index.html and Start the npm

Now we create step by step


1. Setup the package.json, 

Create a folder name "angular applications", under that folder create a file package.json

 package.json
{
    "name": "Angular2",
    "description": "This projects deals with angular samples",
    "version": "1.0.0",
    "scripts": {
        "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
        "lite": "lite-server",
        "postinstall": "typings install",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "typings": "typings"
    },
    "dependencies": {
        "@angular/common": "~2.0.1",
        "@angular/compiler": "~2.0.1",
        "@angular/core": "~2.0.1",
        "@angular/forms": "~2.0.1",
        "@angular/http": "~2.0.1",
        "@angular/platform-browser": "~2.0.1",
        "@angular/platform-browser-dynamic": "~2.0.1",
        "@angular/router": "~3.0.1",
        "@angular/upgrade": "~2.0.1",
        "angular-in-memory-web-api": "~0.1.1",
        "bootstrap": "^3.3.7",
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.8",
        "rxjs": "5.0.0-beta.12",
        "systemjs": "0.19.39",
        "zone.js": "^0.6.25"  
    },
    "devDependencies": {
         "concurrently": "^3.0.0",
         "lite-server": "^2.2.2",
         "typescript": "^2.0.3",
         "typings":"^1.4.0"
    }    
}


 In Above config you may find few key things, the important things are dependencies, devDependencies, scripts, in dependencies we have to add the dependent files which needs to download using the npm package manager, in devdependencies we have to configure additional things like server, typings, typescript version. In scripts section we can configure the postinstall settings and lite server inputs to compile and watch the files





2. Setup the tsconfig.json

Create a file name tsconfig,json , which is a configuration file used for typescript.

tsconfig,json
    
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}





3. Setup the typings.json
    
Create a file named typings.json in which we can define additional typings

typings.json
{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}





4. Create the systemjs.config.js

Now create a system config file which is used to define the basic things like module to be load by System.js, it is basically config file for System.js, Here we can define the paths and there bundles with short names which can be used through out the applications, Create a module pattern function inside that call a System.Config


systemjs.config.js
(function (global) {
    
    System.config({
        
        paths:{
            'npm:': 'node_modules/'
        },

        map: {
            // our app is within the app folder
            app: 'com',
            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
         '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            
    '@angular/platform-browser': 
       'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            
    '@angular/platform-browser-dynamic': 
'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
       
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            // other libraries
            'rxjs':                      'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
         },

    // packages tells the System loader how to load when no filename 
    packages: {
            com: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                defaultExtension: 'js'
            },
            'angular-in-memory-web-api': {
                main: './index.js',
                defaultExtension: 'js'
            }
         }

    });

})(this);





5. Create the main.ts typescript file

Next important thing is we have to create main.ts file , Create a folder name com, then create a file name main.ts under that, Here we have to do the few important things , i.e bootstrap the module which is present under the application, if we have an component in index.html then the module in which it is present needs to be bootstrap, To bootstrap we have to create a platform specific bootstrap named   platformBrowserDynamic , using this we have to bootstrap the module

main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

const platform = platformBrowserDynamic();




6. Run the npm 

Now we have to install the packages using the npm, to do this first we have to install the node package manager in our system, then do the following steps.

  1. open the command prompt
  2. go to the root folder path of your application in your command prompt
  3. type npm install, which will install all packages includes in packages.json later it will run the post install the typings

Now node_modules are created inside your root folder.


7.  Add the index.html file

     Now we have to create a index.html file in the root folder which will load default in angular applications

<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="style.css">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
      
    <script src="lib/jquery.js"></script>
    <script src="node_modules/bootstrap/dist/js/bootstrap.js"></script>
  

    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    
    <script>
      System.import('com').catch(function(err){ 
          console.error(err); 
        });
    </script>

  </head>
  <!-- 3. Display the application -->
  <body>
   
  </body>
</html>




8. Create a component

Next step is to create a component for our application , now we create a helloComponent, first create helloComponent.ts file under "com" folder

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

@Component({
    selector:'hello-app',
    template:'<h1>Hello {{name}}</h1>',
    encapsulation:ViewEncapsulation.None    
})
export class HelloComponent{
    name:string = "Rajesh G";
}





9. Create and Bootstrap a module

Next step is add the helloComponent to the HelloModule and bootstrap that module, Create a hello.module.ts file under the com folder

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { HelloComponent } from'./hello.component'

@NgModule({
    imports:[BrowserModule],
    exports:[],
    declarations:[HelloComponent],
    bootstrap:[HelloComponent]
})

export class HelloModule{
    
}


Now add something configuration in the main.ts to bootstrap the module, adding the HelloModule in the bootstrap

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

const platform = platformBrowserDynamic();

let moduleref = platform.bootstrapModule(HelloModule);




10. Add the component in index.html and Start the npm

        Now we are adding that component in the index.html , inside the body tag

<body>
    <hello-app>Loading...</hello-app>
  </body>


then we have to start the server by following steps,Now run the npm package manager from command prompt

1. Go to the command prompt and iterate to the root folder of your application 
2. Type npm start which will start the server and load the application in browser.




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












From this post you can learn how to setup a basic Angular2 applications, still we can except many changes in stable releases also,to reach a well matured product phase.