Sunday 9 September 2018

Ng5- Excel File download using POST request

Ng5- Excel File download using POST request:
--------------------------------------------

tempalte.html:
-----------
<div (click)="download(modell)" style="margin:50px;border: solid #000">download Excel File in Angualr 5 using POST Request.</div>
  REf:https://stackoverflow.com/questions/49422518/angular-5-download-excel-file-with-post-request
 
component.ts:
-------------
passModel = { /* posting object */ }
download(passModel) {
  //this.loadingOverlayFlag = true;
  this.graphService.DownloadData(passModel).subscribe(result=>{
    // console.log(result);
    this.downloadFile(result,'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'export.csv');
  })
}

downloadFile(blob: any, type: string, filename: string) {

  var binaryData = [];
  binaryData.push(blob);

  const url = window.URL.createObjectURL(new Blob(binaryData)); // <-- work with blob directly

   // create hidden dom element (so it works in all browsers)
   const a = document.createElement('a');
   a.setAttribute('style', 'display:none;');
   document.body.appendChild(a);

   // create file, attach to hidden element and open hidden element
   a.href = url;
   a.download = filename;
   a.click();
}

service.ts:
-----------

DownloadData(model):Observable<any>{
    return new Observable(obs => {
      var oReq = new XMLHttpRequest();
      oReq.open("POST", 'http://localhost:8080/api/downlaod/excel', true);
      oReq.setRequestHeader("content-type", "application/json");
      oReq.responseType = "arraybuffer";
 
      oReq.onload = function (oEvent) {
        var arrayBuffer = oReq.response;
        var byteArray = new Uint8Array(arrayBuffer);
        obs.next(byteArray);
      };
 
      const body = JSON.stringify(model);
      oReq.send(body);
    });
  }

NG 5 - File Upload

NG 5 - File Upload
-------------------
template.html
------------
 <p class="subhead">File Attachement</p>
    <p>
      <strong>Upload file types: .xls</strong>
    </p>
    <div class="form-group" name="uploadBtn">
      <label class="btn btn-primary clear" aria-expanded="false">Upload
        <input type="file" [formControl]="document" (change)="uploadFile($event)" class="form-control-file" aria-describedby="fileHelp">
      </label>
    </div>
component.ts
------------
document = new FormControl()
file;
errorMessage='';
uploadWarning;
uploadSucessData;
  uploadFile(event){
    if (event && event.target && event.target.files && event.target.files.length > 0) {
      this.file = event.target.files[0];
      let fileName = this.file.name;
      let parsedFileName = fileName.split(".");
      let partsLength = parsedFileName.length;
      let extension = parsedFileName[partsLength - 1];
      let size = event.target.files[0].size;
      let fileNameLength = parsedFileName[0].length;

      if (!this.isValidFileSize(size)) {
        //documentFormControl.setErrors({ addDocument_invalidFileSize: true })
        console.log(" invalid File size exceeds")
        this.errorMessage = "  invalid File size exceeds";
        this.uploadWarning = true;
      }
      else if (!this.isValidExtension(extension)) {
       // documentFormControl.setErrors({ addDocument_invalidFileExtn: true })
        console.log(" invalid File Format")
        this.errorMessage = " invalid File Format";
        this.uploadWarning = true;
      }
      else {

        this.service.uploadLocalChanges(this.file, this.file.name).subscribe( response => {
          console.log(response)
          if(response.status == true){
           
            this.uploadSucessData = response.data;
           
          }
          else if(response.status == false){
         
            this.failureItem = true;
         
            this.uploadError = response.errors;
          }
        },
          (error)=>{
          console.log(error)
          })
      }
    }
    }

  isValidExtension(extension) {
    extension = extension.toLowerCase();
    let result = false;
    if (extension && allowedExtension.indexOf(extension) >= 0) {
      result = true;
    }
    return result;
  }

  isValidFileSize(size) {
    let result = false;
    if (size && size <= 1000000) {
      result = true;
    }
    return result;
  }
  commitLocalChanges(){
    let commitData = { data : this.uploadSucessData}
    this.service.commitLocalChanges(commitData).subscribe( data => {
    console.log(data,"commit response")
    },
      (error)=> {
      console.log(error)
      })
  }
  cancelLocalGlossary(){
   // this.uploadErrorMessage = [];
   // this.uploadSucessData = [];
    this.successItem = false;
    this.failureItem =false;
    this.uploadHide = false;
  }
 
 
  Service.ts
  ---------
  uploadLocalG(files: File, name: string): Observable<any> {
    const formData: FormData = new FormData();
    const headers = new Headers();

    formData.append('file', files, name);
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');

    return this.http.post(`http://localhost:8080/apiupload`, formData)
   //return this.http.post('http://localhost:8080/apiupload', formData, option)
     .map(
       res => {
         const data = res;
         return data;
       })
     .catch(error => Observable.throw(error))
}
  commitLocalchange(postData){
    return this.http.post(`http://localhost:8080/apicommit`, postData)
      .map(
        res => {
          const data = res;
          return data;
        })
      .catch(error => Observable.throw(error))

  }

NG5- How to unsubscribe all the service in ngOnDestroy()

NG5- How to unsubscribe all the service in ngOnDestroy()
--------------------------------------------------------

To relase the component, need to unsubscribe in EveryComponent.component.ts
----------------------------------------------------------------------------
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

export class ComponentClass implements OnInit, OnDestroy

subscriptList: Array<Subscription> = [];

 getServiceData(){
 let subscription;
    subscription = this.myService.getData(this.id).subscribe( data =>{
      console.log(data)
 
  },
  (error) =>
  { console.log(error)
  }
);
this.addToSubscriptList(subscription);
}

 addToSubscriptList(subscription) {
    this.subscriptList.push(subscription);
  }
 
 
  ngOnDestroy() {
    this.subscriptionList.forEach(subscription => {
      subscription.unsubscribe();
    })
  }

Ng5- Idle timeout functionality the application

Ng5- Idle timeout functionality the application
-----------------------------------------------
package.json
---------------
"@ng-idle/core": "2.0.0-beta.10",
"@ng-idle/keepalive": "2.0.0-beta.10",

add the do package and do npm install

environment.ts 
--------------
 idleTimeout : 1440,//In second
 waitTimeout: 60,//In second
 
 to provide timeout duration
 

app.module.ts
-------------
import { NgIdleKeepaliveModule } from '@ng-idle/keepalive'; // core dependncy
import { HttpModule } from '@angular/http';                ///for angluar - bug dependencies


import : [
NgIdleKeepaliveModule.forRoot(),
HttpModule
]

app.comoponent.ts
------------------
import { ActivatedRoute, Router } from '@angular/router';
import { Idle, DEFAULT_INTERRUPTSOURCES } from '@ng-idle/core';
import { Keepalive } from '@ng-idle/keepalive';
import { environment } from '../environments/environment';

private idelTimeOut: boolean = false;
  constructor(private router: Router, private route: ActivatedRoute, private idle: Idle, private keepalive: Keepalive){
    this.isOnline = navigator.onLine;
    //console.log(this.isOnline,"online or offline")
    idle.setIdle(environment.idleTimeout);
    //after X seconds of inactivity, the user will be timed out automatically.
    idle.setTimeout(environment.waitTimeout);
    // sets the default interrupts, in this case, things like clicks, scrolls, touches to the document
    idle.setInterrupts(DEFAULT_INTERRUPTSOURCES);

    //Idle + wait timeout pass hence logout automatically
    idle.onTimeout.subscribe(() => {
      console.log('call out logout');
      this.logout();
    });

    //Idle time passed so, show the timeout modal
    idle.onIdleStart.subscribe(() => {
      this.idelTimeOut = true;
    });

    //Do we really need this keepalive?
    keepalive.interval(15);

    this.start();
  }

  start() {
    //Start watching  idle.
    console.log('idle started')
    this.idle.watch();
    this.idelTimeOut = false;
  }

  reset() {
    this.start();
    console.log('reset idle time');
    //this.commonService.pingServer().subscribe();
  }
  logout(){
    alert("Idle timeout called!");
  }

NG5- Share Data using Service as Subject (short hand) and BehaviourSubject

NG5- Share Data using Service as Subject (short hand) and BehaviourSubject
--------------------------------------------------------------------------
Behaviour subject get's called before the receiver component comes to load.
Subject based service used to load if, the receiver component is in DOM

Common.service.ts
------------------
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import {BehaviorSubject, Observable} from "rxjs/Rx";

@Injectable()
export class CommonService {

  private type1 = new Subject<{flag:false}>();
  private type2 = new Subject<{flag:false}>();
  private type3: BehaviorSubject<{}> = new BehaviorSubject({flag:false});

  // method:1
  setValue1(message) {
    this.type1.next(message);
  }
  getValue1(): Observable<any> {
    return this.type1.asObservable();
  }
  // method:2
  swapValue(val){
    this.type2.next(val);
  }
  getcandidateQRow = this.type2.asObservable();
  //method:3
  setValue3(edit){
    this.type3.next(edit);
  }
  getValue3(){
    return this.type3;
  }
 
  }
 

component1-sender.ts
--------------------

inject Service

constructor( private service: CommonService){}

this.service.setValue1(this.selectedTableRow);
this.service.swapValue(this.selectedTableRow);
this.service.setValue3(this.selectedTableRow);


component2-receiver.ts
----------------------

inject Service

constructor( private service: CommonService){

this.service.getCQRowEdit().subscribe(
      res => {
        let temp;
        temp = res;       
        console.log(res,'Behaviour Subject');
      });
    this.addToSubscriptList(subscription);
this.service.getCQRow().subscribe(
      res => {
        let temp;
        temp = res;
        console.log(res, 'subject');
      });
  responed;
service.getcandidateQRow.subscribe( res =>{

      viewRow =>this.responed= viewRow;
      console.log(this.responed,'code elimination subject');
    });
}

NG-access key and value of object using *ngFor

NG-access key and value of object using *ngFor
============================================

Have Object.keys accessible in the template and use it in *ngFor.

@Component({
  selector: 'app-myview',
  template: `<div *ngFor="let key of objectKeys(items)">{{key + ' : ' + items[key]}}</div>`
})

export class MyComponent {
  objectKeys = Object.keys;
  items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };
  constructor(){}
}

Ng5-Lazy-loading-bug-cli-1.7.1 bug:

Ng5-Lazy-loading-bug-cli-1.7.1 bug:
-----------------------------------
angular-cli1.7.1 have issue to laod lazy laoding in string



{ path: 'user-panel', loadChildren: './user-panel/user-panel.module#UserPanelModule', },  -> will give error some time.


to
{ path: 'user-panel', loadChildren: () => UserPanelModule, },

import {UserPanelModule} from '/path-of-module'   in routing.ts
make the lazy loading into preloader module-> load the module as component level - module as component.

Ng5-Dynamic Selectoption - Drop down menu for selecting country then states then district

Ng5-Dynamic Selectoption - Drop down menu for selecting country then states then district
-------------------------------------------------------------------------------------------
template.html
--------------------
  <div>
    <h2>Hello country/ state/ cities </h2>

    <select (change)="countryChange($event)" >
      <option>Select</option>
      <option *ngFor="let c of countries" [ngValue]="c.country">{{ c.country }}</option>
    </select>

    <select (change)="statesChange($event)">
      <option>Select</option>
      <option *ngFor='let state of states' [ngValue]="state.name">{{ state.name }}</option>
    </select>

    <select >
      <option>Select</option>
      <option *ngFor='let city of cities' [ngValue]="city">{{ city }}</option>
    </select>
  </div>

component.ts
--------------- 
 
 countries= [{
"country": "Afghanistan",
      "states": [
                  { "name":"Nurestan", "cities":["c1", "c2", "c3"]  },
                  { "name":"Oruzgan", "cities":["orc1", "oruc2", "oruc3"] },
                  { "name":"Panjshir", "cities":["3c1", "3c2", "3c3"]  }
                ]
    },
    {
"country": "Albania",
"states": [
                  { "name": "Korce" , "cities":["c1", "c2", "c3"] },
                  { "name": "Kukes",  "cities":["orc1", "oruc2", "oruc3"] },
                  { "name": "Lezhe","cities":["orc1", "oruc2", "oruc3"]},
                  { "name": "Shkoder", "cities":["orc1", "oruc2", "oruc3"]},
                  { "name": "Tirane","cities":["orc1", "oruc2", "oruc3"]}
                ]
},
{
"country": "Antarctica",
"states": []
}
]

states= []; cities = [];
countryChange(e){
  console.log(e.target.value)
  this.countries.filter(element => {
if(element.country == e.target.value){
  console.log(element.states[0],"first state")
  this.states = element.states;
}
  });
  this.cities = []
}
statesChange(evt){
  console.log(evt.target.value,this.states)
  this.states.filter( element =>{
if(element.name == evt.target.value){
  this.cities = element.cities;
}
  })
}

how to do angular cli install behind corporate proxy

how to do angular cli install behind corporate proxy
---------------------------------------------------
step: 0:
--------
By default : once installed Node Js without comparny proxy it will set npm registry.
If you want to set global npm regristry follow the step. But out case start from Step:1

npm set registry http://registry.npmjs.org/


Seems it is a certificate expire issue with:

npm registry https://registry.npmjs.org/
in stead run:

delete proxy:
-----------
npm config rm proxy
npm config rm https-proxy


Step 1

Open command prompt of your system (run as administrator).

Step 2

In command prompt, type the below-highlighted command and enter,

C:\windows\system32>ping proxy                                                                                                                         

Step 3

You will find proxy URL of your work environment very similar to the below proxy URL format in the first line,

proxy.[company name].com    or proxy.{extension}.[company name].net

step:4

npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080


Step 5

Once TypeScript is installed successfully, run the below command just to check which TypeScript version is installed,

>tsc –v       

How to share component to multiple modules in Angular2

How to share component to multiple modules in Angular2
===========================================================
Hey Guys,

    In every application some times there were some views which are repeated in the whole application, and for that we have two option:

Either we repeat the same code everywhere in all the views where it’ll be used.
Or we can create a common component and share it to every other view

If the functionality of the repeated view is same everywhere then repeating the code is not a best practice, In my opinion creating a common component and applying it to all different view/module is a great idea, it reduces the code redundancy and make our application neat and clean, also if something gets changed then you have to change it only in one component.

But how can we achieve this in Angular 2 application?

Since in Angular 2 we follow modular design pattern, which means we keep different views in different modules, but the question is how can we share a single component to different modules?

We cannot share a component to different modules by just importing that component inside all the modules, because Angular 2 doesn’t allow us to import single component to different modules, if you try to do this then Angular will throw an error:
    Type X(component) is part of the declarations of 2 modules

 Type X(component) is part of the declarations of 2 modules


So, for solving this problem we create a Shared Module instead of sharing a component, now we share this module in all other modules for this we use import statement and import the shared module in all other modules after this the component will gets automatically shared to all the modules.

Below is the example of how to do it:

SharedModule

@NgModule({
    imports: [
        SomeModule
     ],
    declarations: [
         SharedComponent
    ],
    exports: [
        SharedComponent
    ]
})
 
export class SharedMoule {}
app.module.ts

import { SharedModule } from './shared/shared.module;
 
@NgModule({
    imports: [ SharedModule],
     ...
})

CSS3- Flip to show front back content in html DB -cards

<!DOCTYPE html>
<html>
    <head>
        <title> media test</title>
        <meta charset="utf-8">
        <meta name="keywords" content="test,css, css test">
        <meta name="description" content="A CSS test and review.">
        <meta name="author" content="brandon lind">
        <link rel="stylesheet" media="screen" href="css/main.css">
        <style>
            .parent {
  transition: transform 1s ease-in-out 0s;
  transform-style: preserve-3d;
  width: 100px;
}
.parent:hover {
  transform: rotateY(180deg);
}
.back,
.front {
  width: 100px;
  height: 170px;
  position: absolute;
  top: 0;
  left: 0;
  backface-visibility: hidden;
}
.front {
  background-color: blue;
}
.back {
  background-color: red;
  transform: rotateY(180deg);
}
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="back">
                back
            </div>
            <div class="front">
                front
            </div>
        </div>
    </body>
</html>

Css3 - Show back in sli down whe nHover text DB Card Design 2

<!Doctype html>
<html>
<head>
<style>
// using less preprocessor the css prob is used
.view {
  width: 23%;
  height: 100px;
  margin:0px 0px 0px 15px;
  float: left;
  overflow: hidden;
  position: relative;

  //-webkit-box-shadow: 1px 1px 2px #e6e6e6;
  //-moz-box-shadow: 1px 1px 2px #e6e6e6;
  //box-shadow: 1px 1px 2px #e6e6e6;
  cursor: default;
  background: #fff;
  border: thin solid #ccc;
  //background: #fff url(avatar.png) no-repeat center center;
}
.scard1{
  background:#7AAF3F;
}
.scard2{
  background:#E8892B;
}
.scard3{
  background:#EB2A47;
}
.scard4{
  background:#27699A;
}

.view .mask {
  width: 100%;
  height: 98px;
 // border:thin solid #0f2d51;
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0;
  text-align: center;
  background-color: #fff;
  -webkit-transform: translateY(-200px);
  -moz-transform: translateY(-200px);
  -o-transform: translateY(-200px);
  -ms-transform: translateY(-200px);
  transform: translateY(-200px);
  -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)";
  filter: alpha(opacity=100);
  opacity: 1;
  -webkit-transition: all 0.7s ease-in-out;
  -moz-transition: all 0.7s ease-in-out;
  -o-transition: all 0.7s ease-in-out;
  -ms-transition: all 0.7s ease-in-out;
  transition: all 0.7s ease-in-out;
}
.view .frontText {
  display: block;
  position: relative;
  -webkit-transition: all 0.7s ease-in-out;
  -moz-transition: all 0.7s ease-in-out;
  -o-transition: all 0.7s ease-in-out;
  -ms-transition: all 0.7s ease-in-out;
  transition: all 0.7s ease-in-out;
}
.frontText{
  h5,h2{
    color:#fff;
  }

}
.view:hover .mask {
  -webkit-transform: translateY(0px);
  -moz-transform: translateY(0px);
  -o-transform: translateY(0px);
  -ms-transform: translateY(0px);
  transform: translateY(0px);
}
.view:hover .frontText {
  -webkit-transform: translateY(200px);
  -moz-transform: translateY(200px);
  -o-transform: translateY(200px);
  -ms-transform: translateY(200px);
  transform: translateY(200px);
}
.score-cards{
  .single-card{
    padding:0px;

  }
}
.frontText{
  padding: 1rem;
}

</style>

</head>

<body>

<div class="main">
    <div class="view scard1">
      <div class="frontText">
        <h5>BOX1</h5>
        <h2>3</h2>
      </div>
      <div class="mask">
        <h5>Hover text</h5>
        <div>LDM</div>
        <a class="info">Read More</a>
      </div>
    </div>
  <div class="view scard2">
    <div class="frontText">
      <h5>BOX2</h5>
      <h2>23</h2>
    </div>
    <div class="mask">
      <h5>Hover text</h5>
      <div>LDM</div>
      <a class="info">Read More</a>
    </div>
  </div>
  <div class="view scard3">
    <div class="frontText">
      <h5>BOX3</h5>
      <h2>312</h2>
    </div>
    <div class="mask">
      <h5>Hover text</h5>
      <div>LDM</div>
      <a class="info">Read More</a>
    </div>
  </div>
  <div class="view scard4">
    <div class="frontText">
      <h5>BOX4</h5>
      <h2>9</h2>
    </div>
    <div class="mask">
      <h5>Hover text</h5>
      <div>LDM</div>
      <a class="info">Read More</a>
    </div>
  </div>
</div>

</body>
</html>

Sunday 10 June 2018

Angular 5 - Splash Screen with Css3 Animation

soln:1 - 3 crircle animation
--------------------------------
<dc-root>
      <div id="preloader">
          <div id="loader"></div>
      </div>
</dc-root>

dc-root {
  background-color: #222;
}
#preloader {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1003;
    background: #000000;
    & > div {
      display: block;
      position: relative;
      left: 50%;
      top: 50%;
      width: 150px;
      height: 150px;
      margin: -75px 0 0 -75px;
      border-radius: 50%;
      border: 3px solid transparent;
      border-top-color:darkorchid;
      transform: translate3d(0, 0, 0);
      animation: spin 2s linear infinite; /* Chrome, Firefox 16+, IE 10+, Opera */
}
}
#loader {
    display: block;
    position: relative;
    left: 50%;
    top: 50%;
    width: 150px;
    height: 150px;
    margin: -75px 0 0 -75px;
    border-radius: 50%;
    border: 3px solid transparent;
    border-top-color: #9370DB;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
}
#loader:before {
    content: "";
    position: absolute;
    top: 5px;
    left: 5px;
    right: 5px;
    bottom: 5px;
    border-radius: 50%;
    border: 3px solid transparent;
    border-top-color: darkblue;
    -webkit-animation: spin 3s linear infinite;
    animation: spin 3s linear infinite;
}
#loader:after {
    content: "";
    position: absolute;
    top: 15px;
    left: 15px;
    right: 15px;
    bottom: 15px;
    border-radius: 50%;
    border: 3px solid transparent;
    border-top-color: darkslateblue;
    -webkit-animation: spin 2.5s linear infinite;
    animation: spin 1.5s linear infinite;
}
@-webkit-keyframes spin {
    0%   {
        -webkit-transform: rotate(0deg);
        -ms-transform: rotate(0deg);
        transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
        -ms-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
@keyframes spin {
    0%   {
        -webkit-transform: rotate(0deg);
        -ms-transform: rotate(0deg);
        transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
        -ms-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}    

Soln:2 bg color and 3 dots
----------------------------------
<style>
      dc-root {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;   
        color: pink;
        text-transform: uppercase;
        font-family: -apple-system,
            BlinkMacSystemFont,
            "Segoe UI",
            Roboto,
            Oxygen-Sans,
            Ubuntu,
            Cantarell,
            Helvetica,
            sans-serif;
        font-size: 2.5em;
        text-shadow: 2px 2px 10px rgba(0,0,0,0.2);
      }
      body {
        background: salmon;
        margin: 0;
        padding: 0;
      }
   
      @keyframes dots {
        50% {
          transform: translateY(-.4rem);
        }
        100% {
          transform: translateY(0);
        }
      }
   
      .d {
        animation: dots 1.5s ease-out infinite;
      }
      .d-2 {
        animation-delay: .5s;
      }
      .d-3 {
        animation-delay: 1s;
      }
</style>
   
Loading<span class="d">.</span><span class="d d-2">.</span><span class="d d-3">.</span>

soln:3 single circle 
-----------------------

 <dc-root>
  <!-- loading layout replaced by app after startupp -->
  <div class="app-loading">
    <div class="logo"></div>
    <svg class="spinner" viewBox="25 25 50 50">
      <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/>
    </svg>
</div>
</dc-root>
  <!-- inline spinner styles to be able to display spinner right away -->
  <style type="text/css">
    body, html {
      height: 100%;
    }
    .app-loading {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
    }
    .app-loading .spinner {
      height: 200px;
      width: 200px;
      animation: rotate 2s linear infinite;
      transform-origin: center center;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
    }
    .app-loading .spinner .path {
      stroke-dasharray: 1, 200;
      stroke-dashoffset: 0;
      animation: dash 1.5s ease-in-out infinite;
      stroke-linecap: round;
      stroke: #ddd;
    }
    @keyframes rotate {
      100% {
        transform: rotate(360deg);
      }
    }
    @keyframes dash {
      0% {
        stroke-dasharray: 1, 200;
        stroke-dashoffset: 0;
      }
      50% {
        stroke-dasharray: 89, 200;
        stroke-dashoffset: -35px;
      }
      100% {
        stroke-dasharray: 89, 200;
        stroke-dashoffset: -124px;
      }
    }
  </style>

Tuesday 22 May 2018

CSS3 - Animation best E.g - tranisition and translate

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Original Hover Effects with CSS3</title>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Original Hover Effects with CSS3" />
       
        <link rel="stylesheet" type="text/css" href="css/style_common1.css" />
<link rel="stylesheet" type="text/css" href="css/style55.css" />
<style>
.view {
   width: 300px;
   height: 200px;
   margin: 10px;
   float: left;
   border: 10px solid #fff;
   overflow: hidden;
   position: relative;
   text-align: center;
   -webkit-box-shadow: 1px 1px 2px #e6e6e6;
   -moz-box-shadow: 1px 1px 2px #e6e6e6;
   box-shadow: 1px 1px 2px #e6e6e6;
   cursor: default;
   background: #fff url(../images/bgimg.jpg) no-repeat center center;
}
.view .mask {
   width: 300px;
   height: 200px;
   position: absolute;
   overflow: hidden;
   top: 0;
   left: 0;
}
.view img {
   display: block;
   position: relative;
}


.view h2 {
   text-transform: uppercase;
   color: #fff;
   text-align: center;
   position: relative;
   font-size: 17px;
   padding: 10px;
   background: rgba(0, 0, 0, 0.8);
   margin: 20px 0 0 0;
}
.view p {
   font-family: Georgia, serif;
   font-style: italic;
   font-size: 12px;
   position: relative;
   color: #fff;
   padding: 10px 20px 20px;
   text-align: center;
}
.view a.info {
   display: inline-block;
   text-decoration: none;
   padding: 7px 14px;
   background: #000;
   color: #fff;
   text-transform: uppercase;
   -webkit-box-shadow: 0 0 1px #000;
   -moz-box-shadow: 0 0 1px #000;
   box-shadow: 0 0 1px #000;
}
.view a.info: hover {
   -webkit-box-shadow: 0 0 5px #000;
   -moz-box-shadow: 0 0 5px #000;
   box-shadow: 0 0 5px #000;
}
.view-fifth img {
   -webkit-transition: all 0.7s ease-in-out;
   -moz-transition: all 0.7s ease-in-out;
   -o-transition: all 0.7s ease-in-out;
   -ms-transition: all 0.7s ease-in-out;
   transition: all 0.7s ease-in-out;
}
.view-fifth .mask {
   background-color: rgba(146,96,91,0.3);
   -webkit-transform: translateY(-300px);
   -moz-transform: translateY(-300px);
   -o-transform: translateY(-300px);
   -ms-transform: translateY(-300px);
   transform: translateY(-300px);
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)";
   filter: alpha(opacity=100);
   opacity: 1;
   -webkit-transition: all 0.7s ease-in-out;
   -moz-transition: all 0.7s ease-in-out;
   -o-transition: all 0.7s ease-in-out;
   -ms-transition: all 0.7s ease-in-out;
   transition: all 0.7s ease-in-out;
}
.view-fifth h2 {
   background: rgba(255, 255, 255, 0.5);
   color: #000;
   -webkit-box-shadow: 0px 1px 3px rgba(159, 141, 140, 0.5);
   -moz-box-shadow: 0px 1px 3px rgba(159, 141, 140, 0.5);
   box-shadow: 0px 1px 3px rgba(159, 141, 140, 0.5);
}
.view-fifth p {
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   opacity: 0;
   color: #333;
   -webkit-transition: all 0.2s linear;
   -moz-transition: all 0.2s linear;
   -o-transition: all 0.2s linear;
   -ms-transition: all 0.2s linear;
   transition: all 0.2s linear;
}
.view-fifth:hover .mask {
   -webkit-transform: translateY(0px);
   -moz-transform: translateY(0px);
   -o-transform: translateY(0px);
   -ms-transform: translateY(0px);
   transform: translateY(0px);
}
.view-fifth:hover img {
   -webkit-transform: translateY(300px);
   -moz-transform: translateY(300px);
   -o-transform: translateY(300px);
   -ms-transform: translateY(300px);
   transform: translateY(300px);
}
.view-fifth:hover p {
   -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)";
   filter: alpha(opacity=100);
   opacity: 1;
}

</style>
     
       
    </head>
    <body>
        <div class="container">
           
            <div class="main">
                <!-- FIFTH EXAMPLE -->
                <div class="view view-fifth">
                    <img src="images/1.jpg" />
                    <div class="mask">
                        <h2>Hover Style #5</h2>
                        <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart.</p>
                        <a href="#" class="info">Read More</a>
                    </div>
                </div>
                <div class="view view-fifth">
                    <img src="images/5.jpg" />
                    <div class="mask">
                        <h2>Hover Style #5</h2>
                        <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart.</p>
                        <a href="#" class="info">Read More</a>
                    </div>
                </div>
                <div class="view view-fifth">
                    <img src="images/2.jpg" />
                    <div class="mask">
                        <h2>Hover Style #5</h2>
                        <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart.</p>
                        <a href="#" class="info">Read More</a>
                    </div>
                </div>
                <div class="view view-fifth">
                    <img src="images/7.jpg" />
                    <div class="mask">
                        <h2>Hover Style #5</h2>
                        <p>A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart.</p>
                        <a href="#" class="info">Read More</a>
                    </div>
                </div>
            </div>
        </div>
     
    </body>
</html>

ref: https://tympanus.net/codrops/2011/11/02/original-hover-effects-with-css3/comment-page-7/#comment-475933

Monday 14 May 2018

Angular 2 provides good support for uploading file


Angular 2 provides good support for uploading file. Any third party library is not required.

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">

fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /** In Angular 5, including the header Content-Type can invalidate your request */
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        this.http.post(`${this.apiEndPoint}`, formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data => console.log('success'),
                error => console.log(error)
            )
    }
}
using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"

Ref:
https://www.blogger.com/blogger.g?blogID=4795707642151153385#editor/target=post;postID=5393771942504813896

Angular - modal popup - Bg cover centered ver horizantally

app.module.ts
------------
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { UiComponentsModule } from './ui-components/ui-components.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    UiComponentsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts
-------------
import { Component, ElementRef, ViewChild } from '@angular/core';
....
export class AppComponent {
...
....
showStatusMessage = false;
openModal(){
this.showStatusMessage = true;
}
popupTitle ="success !";
statusMessageText = "open popup working"
showStatusMessageDialogclose(){
this.showStatusMessage = false;
}

app.template.html
----------------

<div><a (click)="openModal()">Open Modal</a></div>

<app-modal [close]="!showStatusMessage" [title]="popupTitle" [msg]="statusMessageText" (closepopupclicked)="showStatusMessageDialogclose()"></app-modal>

ui-components/ui-components.module.ts
-----------------------------------
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModalComponent } from './modal/modal.component';

const uiComponents =[
  ModalComponent
]

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    ...uiComponents
  ],
  exports:[
    ...uiComponents
  ]
})
export class UiComponentsModule { }


ui-components/modal
-----------------
modal.component.ts
---------------
import { Component, Input, Output, OnChanges, OnInit, EventEmitter, ViewEncapsulation, HostListener } from '@angular/core';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent  {


  @Input() title:any = 'modal';
  @Input() msg:any = 'modal';
  @Input() close = modal;
  @Output() closepopupclicked = new EventEmitter();
  constructor(){
  }
  closePopup(){
    //this.close = true;
    this.closepopupclicked.emit(true);
  }
 
  keyboardEvent: any;   
@HostListener('window:keydown', ['$event'])
keyboardInput(event: any) {
this.keyboardEvent = event;
  if (event.keyCode == 27){
console.log("Esc Key press to clsoe current popup");
this. closePopup();
  }
}

}

modal.component.html
-----------------
<div [hidden]="close"  class="popup-bg">
  <div class="modal-popup-frame-container"> 
        <div class="modal-popup-title">{{title}}</div>
        <div class="modal-popup-message" [innerHTML]="msg" ></div>
        <div class="button modal-popup-button" (click)="closePopup()">Close</div>
  </div>
</div>

modal.component.css
----------------------
.popup-bg {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 14;
}

.modal-popup-frame-container{
    position: relative;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    width: 50%;
    z-index:15;
    background: white;
    min-height: 200px;
    border-top: 50px solid green;
    border-radius: 10px;
    box-shadow: 0 0 5px rgba(0,0,0,.3);
}

.modal-popup-title{
    position: relative;
    margin-top: -30px;
    margin-left: 20px;
    font-size: 20px;
    color: white;
float:left;
}
.modal-popup-message{
    top: 20px;
    position: relative;
    margin-left: 20px;
    font-size: 14px;
    line-height: 20px;
    min-height: 70px;
    max-height: 70px;
    width: 100%;
    overflow-y: auto;
    float: left;
    padding-right: 33px;
}
.modal-popup-button{
    position: relative;
    float: right;
    top: 33px;
    right: 18px;
    padding: 11px 22px;
    cursor: pointer;

}
 
   

Thursday 10 May 2018

Ng4-Export JSON to CSV

Ng5- Download JSON to CSV
template.html
-------------
<a id="Download" title="Download " (click)="downloadCSV()">
            <img src="assets/svg/icons/Download.svg" />
</a>

component.ts
------------
import {ExportCSV} from '../../../exportCSV';

construct(private _exportService:ExportCSV){}

Data = Response Array from Web API service data

downloadCSV() {
    this.downloadData = this.Data.map(item => {
          let val =  new Date(item.eeeDate.split(' ')[0]);
          var day = val.getDate();
          var monthIndex = val.getMonth();
          var year = val.getFullYear();
          let months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
          let mm = months[monthIndex];
          item.eeeDate =day +" " + mm + " " + year;
          return item;
    });
let jsonData=this.allData;
    let level=this.url[3];
    let id=this.url[4];
    let header=['header1 Name','h2name','h3 Number','h4 Id','h5','h6 Version','h7  Date'];
    let keys=['h1k1','h2k2','h3k3','h4k4','h5k5','h6k6','h7k7'];
    let filename= 'CDE'; 
    this._exportService.exportCSV(keys,header,jsonData,filename,level,id);


shared->exportCSVService:
------------
import { Injectable } from '@angular/core';

@Injectable()
export class ExportCSV  {
  constructor() {}
  exportCSV(keys,header,jsonData,filename,level,id){
    let filteredData = this.getFilterJSON(keys,jsonData);
    let ReportTitle = filename+ " " +level+" "+id;
    let ShowLabel = true;
    var arrData = typeof filteredData != 'object' ? JSON.parse(filteredData) : filteredData;
    var CSV = '';
    if (ShowLabel) {
      var row = "";
      for (let index=0;index<header.length;index++) {
        row += header[index] + ',';
      }
      row = row.slice(0, -1);
      CSV += row + '\r\n';
    }
    for (var i = 0; i < arrData.length; i++) {
      var row = "";
      for (var index in arrData[i]) {
        row += '"' + arrData[i][index] + '",';
      }
      row.slice(0, row.length - 1);
      CSV += row + '\r\n';
    }

    if (CSV == '') {
      console.log("Invalid data");
      return;
    }
    var fileName = ReportTitle.replace(/ /g, "_");
    var uri = 'data:text/csv;charset=utf-8,' + encodeURI(CSV);
    var link = document.createElement("a");
    link.href = uri;
    link.download = fileName + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
    getFilterJSON(keys,jsonObj){
     let k=[];
     for(let i=0;i<jsonObj.length;i++){
         let item = {};
         for(let m=0;m<keys.length;m++){
         item[keys[m]]=jsonObj[i][keys[m]];
         }
        k.push(item);
       }   
       return k;
      }

Wednesday 11 April 2018

Angular - netninja - Angular 2 Basics

Angular -youtube-Angualr 2 NetNinja
==================================
Video:1 => what Ng2 ?
-------
js framework for dynamic app. compoent based archi tech not typical MVC based.
core feature
compoent, module, directive, service
simple directory app
routing,service, firebase

Video:2 =>the angular CLI
---------
CLI help create new project (core files) upto deployment level Environment
for this need NPM
$ng new ninja-directory

Video:3 => Typescript Intro
-----------
super set of JS. very similar to Js addianaly classes, types, import, export
in TS - > datatype not reassiable. basic types are -> string, number, boolean, any,array

Video:4 => core files overview
-----------
app/src
config
node_module.....

Video:5 => Angular2 components
-----------
App componet
NAv bar compoent
Blog compoent -> sidebar component and Ariticle component

Video:6 => Templates and CSS
----------

 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
if Url not used inside the component itself the dom and Css means need to provide - template and style
style.css is global style sheet. the properties are applciable across the application

Video:7 => creating components
----------
ng g c home

Video:8 => Nested component
-------
angualr 2 - if you need to import the componet means, create index.ts file insde the component. then export the componet
now in angular cli and angualr 4 not required

Video:9 => Ng-content
-----------
app.template.html
<app-home>hello content</app-home>
home.tempalte.html
<p>
  home works!
</p>
<ng-content></ng-content>
o/p with 
home works!
hello content ====> inside the directive data can't show by default.
So, need to provide in sub compnent with <ng-content> direvtive

Video:10 => Data Binding
----------
binding b/w the template and componet

{{ data binding }} string interpolcation
[require]='expression Property binding
(click)="show()" event binding
<input [(ngModel)] ="twoData" two way data binding

Video:11 => property binding
-----------
<input value ="net Ninja"> normal way
<input [value]="net Ninja"> Angular way of property binding

Video:12 =>     Event Binding
-----------

<buton (click)="alrt()">

Video:13 => two way data binding
----------
template to compoent and compoent to template

Video:14 => Input() decorator -> property binding
----------
<app-home [homevalue]="data" >service

Video:15 => Output() event emitter
-----------

Video:16 => Routing
-----------
/
/home
/directory

Video:17 => adding Link to applcation
------
<a rotuerLink="home" > home</a>
const appRoutes : routes [
{path:'home', component: HomeComponent}
]

Video:18 => route params
-----------
import ActivateRoute and make the

{path:'home/:ninja', component: HomeComponent

Video:19 => Directives
-----------
strutural , attribute

Video:20 => *ngFor
--------

Video:21 => pipes
-----------
upper case, date

Video:22 => custom Pipe
---------

 

Tuesday 10 April 2018

Angular 5- POC- techsith Topics with ng4

Angular-youtube-techsith
===================
Source code https://github.com/gnganpath/learningAngular4techsith
topics : Routing, ChildRouting based on url
Serivces, asObservables, BehaviorSubject


Angular 4 Tutorial series of beginners
=======================================
Video:1 -> setup using CLI
----------
node -v -> v6.11.11
npm install -g @angular/cli
to verify angular install
type ng or ng help
crate project with $ng new learningagular4
package.json
------------
All dev and dependecies are mentioned.
dev: agulare cli, karma, zone,
dependecies: angular core, common, http, rxjs
tsconfig.json
-----------
configuration file for compiler option, libra, target:es5

ng serve --open
change the default code and run
ng test will open in localhost:9876 -- some other port and provide the details
before commit your code do the difference
$git diff
$git status
$git add .
$git commit -m "first commit"
$git push -u remote branch

video:2 ->intro to Typescript
--------
typescript is created by microsoft.
Angular1 is MVC based. But want to crate in component archi based.
So, JS don't have component sbased archi. So typescipt will ES6 to transpile ot ES5.

http://www.typescriptlang.org/play/
Ts - data type
let x = 'hi;
x=2;  Type error string not assignable to number error.
But in JS
var x = 'hi';
x = 2; reassignable. not give error in string and number.
So, to solve  this issue,
let x;
x='hi'; then x =2. not error.

But TS standard is => let x:number =2;
Data Types in TS are => string, numberm, boolean, any; [array, null, undefined, void, enum]
public, private, protected access modifier

class car{
public maxSpeed:numner;
private color:string;
protected price:number;
}
class Toyota extends car{
    constructor(maxspeed, color,price ){
    this.maxspeed = maxspeed;  
    this.color = color;  // error. private var we can accesswith getter and setter method.
    this.price = price;
    }
}
public and protected variable are access thorugh subclass not private variable.

Video:3 -> components using cli
----------
component in angular is heart of app.
$ng new learningagular4 from video:1
$ng g c main-container
compontnent.ts
names = ['kt','sa', 'hcl','trz']
maincontainer.html
    <app-outer [outername]="names"></app-outer>
template.html
    {{names }} == > kt,sa,hcl,trz -->even names is arrya while to do interpolation its will be string
$ng g c outer
outer.component.ts
 @Input() outername;
outer.template.html
 <div>{{ outername}}</div>
$ng g inner
inner.component.ts
import { Component, OnInit,Input ,Output,EventEmitter} from '@angular/core';
@Input() innername;
@Output() eventFromInner = new EventEmitter<string>();
sendtoOuter(){
    console.log('emit')
    this.eventFromInner.emit(this.innername);
}
inner.html
<div class="inner">
  inner compoent
  <span class="name">name: {{innername}} </span>
  <button (click)="sendtoOuter()">send to outer</button></div>
 
modify outer

outer.component.ts
 name = '';
 @Input() outername;
  eventFromInner(passed:string){
    this.name = passed;
  }
outer.template.html
 selected : {{name }}
  <div>array names: => {{ outername}}</div>
  <app-inner *ngFor="let name of outername" [innername]="name" (eventFromInner)="eventFromInner($event)"></app-inner>

Conculstion: pass data from inner to outer and alos pass to main-conintainer
child to parent also grandparent

Video:5 angular4/5 HTTP GET/POST requests
----------
import the HttpClientModule in app.module.ts
next need to create server api file.
Same like myjson API, through github we can create and maintain the file like live API

https://github.com/techsithgit/json-faker-directory/profiles/name?=john

using httpInterceptorModule we can do the post opearaiton.

Video:6 => Routing
--------

Home page, about page, user page... inside user -user details page also
If not valid routing page also goto home page

const appRoutes : Routes =[
 
  { path:'home', component:HomeComponent },
  { path:'about', component:AboutComponent },
  { path:'user', children:
    [
      { path: 'list', component:UserlistComponent,
        children: [
          {path: 'detail/:name', component:UserComponent}
        ]
      }
    ]
  },
  { path:'', redirectTo:'/home', pathMatch: 'full'},
  { path:'**', redirectTo:'/home', pathMatch: 'full'}
]

Video:7  =>  Services
-----------
Share data between 2 services


Video:8 => services Data sync with Observable and behavior subject
-----------
$ng g c one
$ng g c two
$ng g service user
inside UserService ->
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
BehaviorSubject help us to front forth between front end and backend communication
need to broadcast to change the value updated by other component
import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';

@Component({
  selector: 'app-two',
  templateUrl: './two.component.html',
  styleUrls: ['./two.component.css']
})
export class TwoComponent implements OnInit {
  user;
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.cast.subscribe( user => this.user = user)
  }

}

one.tempalte.html
<input type="text" [(ngModel)] = "editoneUser" > <button (click)="edittheUser()">change</button>
one.component.ts
import { UserService } from '../user.service';
export class OneComponent implements OnInit {
 user:string;
 editoneUser;
  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.cast.subscribe( user => this.user = user)
  }
  edittheUser(){
    this.userService.editUser(this.editoneUser)
  }

}

Video:9 => Unit test cases
-----------
unit test, acceptance test e2e test
jasmine, karma, protractor
jasmine  behavior driven
karma help to run test cases in multiple brwoser
jsmine help to do structural code for better performance level

We can able to change the browser testenvironemnt using, karma-firefox-launcher, firefox browser

to install firefox brwoser enable
$npm install karma-firefox-launcher --save-dev

Video:10=> sass(scss), less to your angular project
---------
$ ng new projectName --style=scss
 to change sacc to less

$ng set defaults.stylesheet less -> automatically change the property to less

Video:11 => Angular e2e testi protractor
--------




Ng5- Diff type of routerLink implmentation

Diff type of routerLink implmentation
============================
<nav>
    <a routerLink='/home'></a>
    <a routerLink='/about'></a>
</nav>

case:1
-----
<div *ngFor="let user of userList" [routerLink]="['detail', uer.name]"> {{ user.name }} </div>

case:2
-----
(click)="showUserDetails(user)"

Incase we do the navigation from component function means
 showUserDetails(user){
    this.router.navigate(['user', user.login]);
  }


to make the router navgation implement  routerLink='/home'
If you use parameter passing in router link [routerLink]="['detail', uer.name]"

Sunday 8 April 2018

Angular5 - POC - routing - route params, RxJs Observable with service, tamplate binding, Event binding, Material desing impl

Angular5 POC
============
RxJs Observable with service
tamplate binding, Event binding,
Material desing imple
routing - route params
github link : https://github.com/gnganpath/Angular-6videos-thatJsdude

video:1 -> Installation and requirement software - Local dev environment
----------
Download node js , download and install VS code follow the agular cli version
npm install -g @angular/cli
ng new PROJECT-NAME
cd PROJECT-NAME
ng serve      -> no need of npm install is required here.
ng serve --host 0.0.0.0 --port 4201


video:2 -> component, tempalte binding, Event Handler
----------
bangularbangk$ ng g c circular

inside app.hml - template binding
bind the circular template using <app-circular>

app-circular.html
(click)="changeTextEventHandler()"

app.component.ts
public changeTxt = "initial text";

ngOnInit(){
this.changeTxt = "update text in OnInt";
}

changeTextEventHandler(){
this.changeTxt = "Event handler in child component";
}

video:3 -> Service, Observable, RxJS
----------

bangularbangk$ ng g service github/github

RxJs/Observale ->
app.module.ts
import { HttpClientModule } from '@angular/common/http';
...
imports: [
    BrowserModule,
    HttpClientModule
  ],

github.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map'
@Injectable()
export class GithubService {
  constructor(private http: HttpClient) { }
  getUser(searchText): Observable<any>{             // rxjs - observable call for API
    const url= 'http://api.github.com/search/users?q='+searchText;
    return  this.http.get(url).map(
      res => {
        const data = res;
        console.log(data)
        return data;
      }
    )
  }
}

search.html
<input type="text" (keyup)="onKeyup($event)">
<button (click)="getUsers()">Search</button>
<p>{{ searchCount }}</p>
<ol *ngIf="searchResult">
  <li *ngFor="let user of searchResult.items">{{ user.login }}</li>
</ol>

search.component.ts
import { Component, OnInit } from '@angular/core';
import {GithubService} from '../github/github.service';
 searchText;
  searchResult;
  searchCount;
  ....
  ....
  constructor(private githubService:GithubService) { }
   onKeyup(event){
    this.searchText = event.target.value;
  }
  getUsers(){
    console.log(this.searchText)
    this.githubService.getUser(this.searchText).subscribe(
      res =>{
       // console.log(res)
       this.searchResult = res;
       this.searchCount = res.total_count;
      }
    )};

Video:4 -> Angular2 Material Design

bangularbangk$ npm install --save @angular/material @angular/cdk

app.module.ts
import { MatCardModule } from '@angular/material/card';
....
 imports: [
    BrowserModule,
    HttpClientModule,
    MatCardModule
  ],
 
 
search.html
<div *ngIf="searchResult">
<mat-card class="example-card"  *ngFor="let user of searchResult.items">
  <mat-card-header>
    {{ user.login }}   
  </mat-card-header>
  <img class="profile-image" mat-card-image [src]="user.avatar_url" alt="Photo of a Shiba Inu">
  <mat-card-content>
    content
  </mat-card-content>
</mat-card>
</div>


Video:5 -> Routing, multiple routing, pass a route parameter, load data based on routing
--------

contnents
------------
<base href>
Router imports
Configuration
Router outlet
Router link
Router state
Summary

need to use base-href
index.html
<base href="/">

create appRoutes.ts

import { Routes } from '@angular/router';
import { CircularComponent } from './circular/circular.component';
import { SearchComponent } from './search/search.component';

export const appRoutes: Routes = [
    { path:'circular', component:CircularComponent },
    { path:'search', component:SearchComponent}
]

routeParams implementation in appRoutes.ts

import { Routes } from '@angular/router';
import { CircularComponent } from './circular/circular.component';
import { SearchComponent } from './search/search.component';
import { UserComponent } from './user/user.component';

export const appRoutes: Routes = [
    { path:'circular', component:CircularComponent },
    { path:'search', component:SearchComponent},
    { path:'user/:userId', component:UserComponent}
]
app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { appRoutes } from './app.routes';
.....

import: [
RouterModule.forRoot(appRoutes),
BrowserModule,
HttpClientModule
]

app.html


<router-outlet></router-outlet>       <!--  to implement router in our applicaiton -->

goto localhost:4200/search

find one result  and click
search.html
   <button  mat-button (click)="showUserDetails(user)">{{ user.login }}   </button>
  
search.component.ts
import { Router } from '@angular/router';
 showUserDetails(user){
    this.router.navigate(['user', user.login]);
  }

github.service.ts
.....

  getUserDetails(userId):Observable<any>{
    const url  = 'https://api.github.com/users/'+userId;
    return this.http.get(url).map(
      res =>{
        const user = res;
        return user;
      }
    )
  }
 
user.component.ts
import { ActivatedRoute } from '@angular/router';
....
private userDetail;

  constructor( private activatedRouter:ActivatedRoute, private githubService: GithubService) { }

  ngOnInit() {
    const userId = this.activatedRouter.snapshot.params['userId'];
    console.log(userId)
    this.githubService.getUserDetails(userId).subscribe(
      res =>{
        this.userDetail = res;
        console.log(this.userDetail)
      }
    )
  }
 
 
user.html
<h1>User Details page</h1>
<div *ngIf="userDetail">
  <h4>{{userDetail.name}}</h4>
  <p>email : {{userDetail.email}}</p>
  <small>followers: {{userDetail.followers}}</small>
</div>


Video:6 -> pipes, Debug angular 2, build for proeduction
----------
simple default pipes
<h4>{{userDetail.name | uppercase}}</h4>
  <p>email : {{userDetail.email}}</p>
  <small>followers: {{userDetail.followers}}</small>
  <p>created at:{{userDetail.created_at | date }}</p>
 
For Debugging:

Install chrome Augury plugin

 angular tree, state of the compoent, compoennt dependencies



Ref: ThatJsdude

Friday 6 April 2018

Javascript - TicTacToe Game - Dynamic



<html>
<title>Tic Tac Toe</title>
<head>
<style>


*{
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box; 
  box-sizing: border-box;
}

select {
    padding:3px;
    margin: 0;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px;
    -webkit-box-shadow: 0 3px 0 #ccc, 0 -1px #fff inset;
    -moz-box-shadow: 0 3px 0 #ccc, 0 -1px #fff inset;
    box-shadow: 0 3px 0 #ccc, 0 -1px #fff inset;
    background: #f8f8f8;
    color:#888;
    border:none;
    outline:none;
    display: inline-block;
    -webkit-appearance:none;
    -moz-appearance:none;
    appearance:none;
    cursor:pointer;
    width:100px;
}


.minContainer {
    padding: 20px;
    padding-right: 30px;
    position: absolute;
}

table {
    border-collapse:collapse;
    table-layout: fixed;
    border-spacing: 0;
    width:250px;
    height:300px;
    margin-right:5px;
}
.td {
    border: 2px solid #cccccc;
    font-size:20px;
    font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    color:#ccc;
    line-height: 1.428571429;
    width: 30px;
    height: 32px;
    min-width: 32px;
    max-width: 302px;
    min-height: 32px;
    max-height: 32px;
    text-align: center;
}

.X{
    background-color: #FF8362;   
}

.O{
    background-color: #BB7365;
}


</style>
</head>
<body onload="fnLoad()">
        <div class="container">
                <div>
                        <select id="grid">
                        </select>
                        <button name="NewGame" class="newGame" value="Start a New Game" onClick="fnNewGame()">Start a New Game</button>
                </div>
                <div class="minContainer">
                        <table class="row" id="game"></table>
                </div>
        </div>
<script>


var turn = 'X';
var score = {
    'X': 0,
    'O': 0
};
var gridValue = 0;

function fnLoad() {
    var select = document.getElementById("grid");
    for (i = 3; i <= 100; i += 1) {
        var option = document.createElement('option');
        select.options[select.options.length] = new Option(i + ' X ' + i, i);
    }

    addEvent(document.getElementById("game"), "click", fnChoose);

    fnNewGame();
}

function addEvent(element, eventName, callback) {

    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
}

function fnChoose(e) {
    if (e.target && e.target.nodeName == "TD") {
        var targetElement = document.getElementById(e.target.id);
        var prevTurn;
        if ((targetElement.className).indexOf("disabled") == -1) {
            targetElement.innerHTML = turn;
            targetElement.classList.add('disabled');
            targetElement.classList.add(turn);
            score[turn] += 1;
            prevTurn = turn;
            turn = turn === "X" ? "O" : "X";
            if (fndecide(targetElement, prevTurn)) {
                alert(prevTurn + ' has won the game');
                fnNewGame();
            } else if ((score['X'] + score['O']) == (gridValue * gridValue)) {
                alert('Draw!');
                fnNewGame();
            }
        }
    }
}

function fndecide(targetElement, prevTurn) {
    var UL = document.getElementById('game');
    var elements, i, j, cnt;
    if (score[prevTurn] >= gridValue) {
        var classes = targetElement.className.split(/\s+/);
        for (i = 0; i < classes.length; i += 1) {
            cnt = 0;
            if (classes[i].indexOf('row') !== -1 || classes[i].indexOf('col') !== -1 || classes[i].indexOf('dia') !== -1) {
                elements = UL.getElementsByClassName(classes[i]);
                for (j = 0; j < elements.length; j += 1) {
                    if (elements[j].innerHTML == prevTurn) {
                        cnt += 1;
                    }
                }
                if (cnt == gridValue) {
                    return true;
                }
            }
        }
    }
    return false;
}

function fnNewGame() {
    var gameUL = document.getElementById("game");
    if (gameUL.innerHTML !== '') {
        gameUL.innerHTML = null;
        score = {
            'X': 0,
            'O': 0
        };
        turn = 'X';
        gridValue = 0;
    }
    var select = document.getElementById("grid");
    gridValue = select.options[select.selectedIndex].value;
    var i, j, li, k = 0,
        classLists;
    var gridAdd = +gridValue + 1;

    for (i = 1; i <= gridValue; i += 1) {
        tr = document.createElement('tr');
        for (j = 1; j <= gridValue; j += 1) {
            k += 1;
            li = document.createElement('td');
            li.setAttribute("id", 'li' + k);

            classLists = 'td row' + i + ' col' + j;

            if (i === j) {
                classLists = 'td row' + i + ' col' + j + ' dia0';
            }

            if ((i + j) === gridAdd) {
                classLists = 'td row' + i + ' col' + j + ' dia1';
            }

            if (!isEven(gridValue) && (Math.round(gridValue / 2) === i && Math.round(gridValue / 2) === j))
                classLists = 'td row' + i + ' col' + j + ' dia0 dia1';

            li.className = classLists;
            tr.appendChild(li);

        }
        gameUL.appendChild(tr);
    }
}


function isEven(value) {
    if (value % 2 == 0)
        return true;
    else
        return false;
}

</script>       
</body>
</html>

React + Typescript_ Module federation _ Micro Front end -Standalone and integrated

Module Federation The Module Federation is actually part of Webpack config. This config enables us to expose or receive different parts of t...