Saturday 29 July 2017

NG4/2 - Export json data to CSV in Angular (in Front end) / component.ts

NG4/2 - Export json data to CSV in Angular in Front End / component.ts
============================================
compose CSV from Component from JSON multi array and print data information one by one with 
corresponding header also one empty row Gap
Based on json response make the CSV file. Multi level json response object Iteration and Export to CSV
exportCSV_data.json
-------------------
{
"sections": {
"table1": [{
          "table1column1": "t1c1",
          "table1coloumn2": "t1c2"
          },
          {
          "table1column1": "t12c1",
          "table1coloumn2": "t12c2"
          }],
"table2": [{
        "table2column1": "t2c1",
        "table2column2": "t2c2",
        "table2column3": "t2c3",
        "table2column4": "t2c4"
       
        },
        {
        "table2column1": "t22c1",
        "table2column2": "t22c2",
        "table2column3": "t22c3",
        "table2column4": "t22c4"

         },
         {
          "table2column1": "t22c1",
          "table2column2": "t22c2",
          "table2column3": "t22c3",
          "table2column4": "t22c4"
         
          }],
"table3": [{
          "table3column1": "t3c1",
          "table3column2": "t3c2",
          "table3column3": "t3c3"
         
          },
          {
          "table3column1": "t32c1",
          "table3column2": "t32c2",
          "table3column3": "t33c3"
          }]
}
}


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

<div (click)="downloadCSVfromJSON()"> Download CSV file from JSON API response </div>


app.service.ts
---------------
import {Injectable} from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class AppService {


  constructor( private http: Http) { }
  getJSONresponse(...agrs)Observable<any> {
let url =domainURL;
var argslength=args[0].length;
let itemName=args[0][argslength-2];
let itemId=args[0][argslength-1];
//return this.http.get(url+`${itemName}/${itemId}`)
return this.http.get(url+itemId)
.map(this.extractData)
.catch(this.handleError);
//.map(res => res.json());

}

 private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

   private handleError (error: any) {
    let errMsg = (error.message) ? error.message :
    error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

app.component.ts
------------------
import { Component, NgModule, ViewContainerRef, ViewEncapsulation, ElementRef} from '@angular/core';
@component({
'selector':'app',
'styleUrls:['app.style.css'],
'templateUrl:['app.template.html']
})

export class Appcomponet {

JSON_API_Response:any;
url;  // router url 
constructor(private _servcie:appService){
this._servcie.getJSONresponse(this.url).subscribe( (data => any) =>{ 
if(data.success){
this.JSON_API_Response = data.JSONValue;
}else{
console.lgo('API Response Fail')
}
});
}

downloadCSVfromJSON(){
if(this.JSON_API_Response){
let jsonData = this.JSON_API_Response;

let Table1Key = ['table1column1', 'table1column2'];
let Table1Header = ['Table1 Column1', ' Table1 column 2'];
let Table1JSON = jsonData.section.table1;

let Table2Key = ['table2column1', 'table2column2','table2column3', 'table2column4'];
let Table1Header = ['Table1 Column1', ' Table1 column 2','Table2 column3', 'Table2 column4'];
let Table2JSON = jsonData.section.table2;

let Table3Key = ['table3column1', 'table3column2', 'table3column3'];
let Table3Header = ['Table3 Column1', ' Table3 column 2',, 'Table3 Column3'];
let Table3JSON = jsonData.section.table3;


let filteredData = this.getCSV(Table1Key,Table1Header,Table1JSON, Table2Key,Table2Header,Table2JSON, Table3Key,Table3Header,Table3JSON);
let ReportTitle = filename+ " " +level+" "+id;
let ShowLabel = true;
var arrData = typeof filteredData != 'object' ? JSON.parse(filteredData) : filteredData;
var CSV = '';
//below commnad retric first line of table 1 column 

// if (ShowLabel) {
//   var row = "";
//   for (let index=0;index<Table1Header.length;index++) {
//     row += Table1Header[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);
 }
}

getCSV(Table1Key,Table1Header,Table1JSON, Table2Key,Table2Header,Table2JSON, Table3Key,Table3Header,Table3JSON){

let k=[];  let newlineItem = {}
              let title=['Table 1 Information '];
              k.push(title)
              k.push(Table1Header)
 for(let i=0;i<Table1JSON.length;i++){
 let item = {};
 for(let m=0;m<Table1Key.length;m++){
 item[Table1Key[m]]=Table1JSON[i][Table1Key[m]];
 }
 k.push(item);
 }
 
k.push(newlineItem); k.push(newlineItem)
title =['table 2 information in single line'];
k.push(title)
k.push(Table2Header)
for(let i=0;i<Table2JSON.length;i++){
 let item = {};
 for(let m=0;m<Table2Key.length;m++){
 item[Table2Key[m]]=Table2JSON[i][Table2Key[m]];
 }
 k.push(item);
 }
            
k.push(newlineItem); k.push(newlineItem)
title =['table 3 information in single line'];
k.push(title)
k.push(Table3Header)
for(let i=0;i<Table3JSON.length;i++){
 let item = {};
 for(let m=0;m<Table3Key.length;m++){
 item[Table3Key[m]]=Table3JSON[i][Table3Key[m]];
 }
 k.push(item);
 }
           
}

}
REf: https://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable

JS - Download CSV from JSON

JS - Download CSV from JSON
-----------------------------
Single Array of JSON compose in CSV file

html
-------
<div Onclick="downloadCSV()"> CSV Format Download </div>

API.json
-------
"sections": {
"table1": [{
          "table1column1": "t1c1",
          "table1coloumn2": "t1c2"
          },
          {
          "table1column1": "t12c1",
          "table1coloumn2": "t12c2"
          }]
}

<script>
var jsonData = data.section.table1; // compose  csv data

var keys = ['table1column1','table1coloumn2'];
var header = ['Table1 Column1', 'Table1 column2']


downloadCSV(){

let filteredData = this.getCSV(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 = "";
 
 //CSV column header is composing here and assamble in row1,column1
      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);

}

getCSV(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;

}

Saturday 15 July 2017

NG4 - Add one new key value and remove existing key valye from Object of Array [object, object ]

NG4 - Add one new key value and remove existing key valye from Object of Array [object, object ]
------------------------------------------------------------------------------------------

InitialArray = [{"key1":"val1", "key2": "val2"}, {"key1":"val11","key2":"val21"}]

Drop Key1/val1 and add Key3/Val3 

ExpctedArray =  [{"key3":"val3", "key2": "val2"}, {"key3":"val31","key2":"val21"}]

Using Angular4/2 Arrow fundtion with ForEach Loop

this.InitialArray.forEach(el => {
        var existingObject = el;
//delete existingObject["key1"];
delete existingObject.key1;
Object.assign(existingObject, {
key3:this.valu3   //'valu3' in this.valu3. Key3 no need of 'key3' Quotes (')
});
   });


NG4- add/ Remove one more key value of Existing object
=======================================================
With the new ES6 method Object.assign, much of the repeated boilerplate can be eliminated. Example:

var existingObject = {
    firstValue: 'hello'
};

/* some time later... */

Object.assign(existingObject, {
  secondValue: 'world' });
  
Ref: https://stackoverflow.com/questions/25777499/short-hand-to-add-many-key-value-pairs-to-an-existing-javascript-object

Remove:
------
// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If a JavaScript shell, it's as easy as:

delete object.keyname;

Ref: https://stackoverflow.com/questions/3455405/how-do-i-remove-a-key-from-a-javascript-object


NG4- ng-content

NG4- ng-content 
----------------

Display for popup content based on the auto/adjusted content
Base-popup.html
------------------
<div (click)="showngContnet()"> template html contnet </div>
<dynamic-popup [popuptitle]="title" (closed)="close()" [baseclose]="basepopupcloseflag">
    <div *ngIf="PopupContent">
        <label for="textarea">Comments :</label>
        <textarea maxlength="30" placeholder="Enter any comments #textAreaInput></textarea>
        <div style="float:right">
            <button [ngClass]="{'button':trueFlag, 'diable-button':!bydefaultFalse}" (click)="send(textAreaInput.value)">Submit</button>
        </div>
    </div>
</dynamic-popup>

Base-popup.component.ts
------------------------

import { Component, ViewContainerRef, ViewEncapsulation, ElementRef } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

basepopupcloseflag = flase;

export class BasePopupComponent {

showngContnet(){
this.basepopupcloseflag = true;
}

close(){
this.basepopupcloseflag = false;
}
}
dynamic_popup-component.ts
--------------------------

import { Component, Input, Output, OnChanges, OnInit, EventEmitter, ViewEncapsulation, HostListener } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'dynamic-popup',
  styleUrls: ['dynamic-popup.component.scss'],
  templateUrl: 'dynamic-popup.component.html',
  encapsulation: ViewEncapsulation.None,
})
export class DynamicPopUp implements OnChanges, OnInit {

  @Input() popuptitle:any = 'test';
  @Output() closed = new EventEmitter();
  constructor(){

  }
  closeModal(){
    this.closed.emit('close');
  }

  }
  
dynamic-popup.html
--------------------- 
<div [hidden]="!close" class="popup-bg">
    <div class="container">      
            <div class="popup-title">{{popuptitle}}</div>
            <button aria-hidden="true"  class="close" data-dismiss="modal" (click)="closeModal()" type="button">×</button>
             
            <ng-content></ng-content>
            
        </div>
    </div>
</div>


Ng4- Filter / Remove particular item from Array - in details object as one item [object, object]

Ng4- Remove item from Array - indetails  object as one item [object, object] 
---------------------------------------------------------------
Filter the selected data 

removeArrayItem(objectitem){

this.totalArrayData = this.totalArrayData.filter(item => item.Id !== objectitem.id);
 console.log( this.totalArrayData)
}


Friday 14 July 2017

JS - merge 2 arrays of objects in JavaScript

JS - merge 2 arrays of objects in JavaScript
================================
soln1: Array.prototype.push.apply(arr1,arr2);
soln2: arr1 = arr1.concat(arr2);

eg: 
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

Array.prototype.push.apply(arr1,arr2); 

console.log(arr1); 

Output:

[{"name":"lang","value":"English"},
{"name":"age","value":"18"},
{"name":"childs","value":"5"},
{"name":"lang","value":"German"}

Ref: https://stackoverflow.com/questions/7146217/merge-2-arrays-of-objects