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

Friday, 23 June 2017

NG4- Custom Pipe - filter

NG4- Custom Pipe | - ng1 filtering  - Angular 2 beta version system based code fyi
==================================
Custom Filter 
==============


app.component.tpl.html
----------------------

Message:
<input type="text" [(ngModel)]="message">
<br> Translated: {{(message | translate) | nvl:'N/A'}}

Here >=> traslate and nvl are custome filetrs. Need use the same naem for filter @pipe ->name
translate.pipe.ts               ==> custome filter no1
------------------
import {Pipe, PipeTransform, Inject} from 'angular2/core';
import {MessageService} from '../service/message.service';

@Pipe({
  name: 'translate',
  pure: false
})
export class TranslatePipe  implements PipeTransform{

private messageBundle:any;
private request:any;
    
    constructor(private _messageService: MessageService){
        this._messageService = _messageService;
        this.messageBundle = {};
    }
    
    transform(value:string, args:string[]):any {           // transform is the expected conversion method
        if(!this.request){
            this.request = this._messageService.getBundle();
            this.request.subscribe(
                data => this.messageBundle = data
             );
        }
        
        return this.messageBundle[value];
    }
}

nvl.pipe.ts                  ==> custome filter 2
-------------
import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({
  name: 'nvl',
  pure: true
})
export class NvlPipe  implements PipeTransform{
    
    constructor(){}
    
    transform(value:string, args:string[]):any {
        return value?value : args[0];
    }
}


app.component.ts
------------------
import {Component} from 'angular2/core';
import {TranslatePipe} from './pipe/translate.pipe';
import {NvlPipe} from './pipe/nvl.pipe';

@Component({
  selector: 'app-component',
  templateUrl: 'src/app.component.tpl.html',
  pipes: [TranslatePipe, NvlPipe]
})
export class AppComponent {}

message.service.ts
-----------------------
import {Injectable} from "angular2/core"
import {Http} from 'angular2/http';
import 'rxjs/Rx'

@Injectable()
export class MessageService{
    constructor(http: Http){
        this.http = http;
    }
    getBundle (){
        return this.http.get('./src/bundle.json').map(res => res.json());
    }
}






index.html
------------
<!DOCTYPE html>
<html>

<head>
    <title>Custom Pipe Example</title>

    <!-- libraries -->
    <script src="https://rawgithub.com/systemjs/systemjs/0.19.6/dist/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2.dev.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/http.dev.js"></script>

    <script>
        System.config({
            transpiler: 'typescript',
            typescriptOptions: {
                emitDecoratorMetadata: true
            },
            packages: {
                'src': {
                    defaultExtension: 'ts'
                }
            }
        });

    </script>

    <script>
        System.import('src/boot');

    </script>

</head>

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

</html>

CSS3 - Focus input animation effects - half -vertical border

 CSS3 - Focus input animation effects - half -vertical border
 ============================================================

 <body>
 <div class="input-wrapper">
  <input type="text" class="inputText" required/>
  <span class="floating-label">Your email address</span>
</div>
</body>

<style>
input:focus ~ .floating-label,
input:not(:focus):valid ~ .floating-label{
  top: 8px;
  bottom: 10px;
  left: 20px;
  font-size: 11px;
  opacity: 1;
}


.floating-label {
  position: absolute;
  pointer-events: none;
  left: 20px;
  top: 18px;
  transition: 0.2s ease all;
}
.input-wrapper {
  position: relative;
}
input{
font-family: Helvetica, Arial, sans-serif;
  font-weight: 300;
  width: 300px;
  border-radius: 2px;
  border: none;
  padding-left: 7px;
  height: 34px;
  font-size: 14px;
  color: #aaa;
  margin-top: 10px;
  margin-bottom: 5px;
}
input:focus {
  outline: none;
  box-shadow: none;
}
.input-wrapper:after {
  position: absolute;
  border: 1px solid #ccc;
  border-top: none;
  height: 5px;
  width: 100%;
  bottom: 6px;
  left: 0;
  content: "";
}
body{width:300px;}

</style>

NG4 - http-DELETE = DELETE Data Access service

NG4 - http-DELETE = DELETE Data Access service
=========================================
import { Component,Output,OnInit,Input, EventEmitter } from '@angular/core'

deleteProduct.component.ts
------------------------

@Component({
selector:'deleteHttp',
styleUrls: ['./deleteHttp.scss'],
templateUrl: './deleteHttp.html',
})

export class DeleteHttpComponent implements OnInit{

...
constructor(private productService: ProductService) { }
...
deleteProduct(id: number): void {
this.productService.postProduct(id)
.subscribe(
(product: IProduct) => this.onProductRetrieved(product),  
// ---> Instead of this (data:any)=>{ if(data.success){ //true } else { //false }}
(error: any) => this.errorMessage= <any>error
);
}



postProduct.service.ts
----------------------
...
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';


...
@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
deleteProduct(id: number): Observable<Response> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});
letoptions = newRequestOptions({ headers: headers });
consturl= `${this.baseUrl}/${id}`;
return this.http.delete(url, options);
}
}
private extractData(res: Response) {
    let body = res
    return body || {} ;
  }
   private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    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);
  }

NG4 - http- UPDATE = UPDATE Data Access service

NG4 - http- UPDATE = UPDATE Data Access service
=========================================
import { Component,Output,OnInit,Input, EventEmitter } from '@angular/core'

updateProduct.component.ts
------------------------

@Component({
selector:'updateHttp',
styleUrls: ['./updateHttp.scss'],
templateUrl: './updateHttp.html',
})

export class UpdateHttpComponent implements OnInit{

...
constructor(private productService: ProductService) { }
editProduct: void {
this.productService.updateProduct(p)
.subscribe(
() => this.onSaveComplete(),
(error: any) => this.errorMessage= <any>error
);
}
}

}

postProduct.service.ts
----------------------
...
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';


...
@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
updateProduct(product: IProduct): Observable<IProduct> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});
letoptions = newRequestOptions({ headers: headers });

consturl= `${this.baseUrl}/${product.id}`;
return this.http.put(url, product, options)
            // post also we can do ,but for consdition based we trying http.put
.map(() => product).catch(this.handleError);
}
}

private extractData(res: Response) {
    let body = res
    return body || {} ;
  }
   private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    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);
  }

NG4 - http-POST = POST Data Access service

NG4 - http-POST = POST Data Access service
=========================================
import { Component,Output,OnInit,Input, EventEmitter } from '@angular/core'

postProduct.component.ts
------------------------

@Component({
selector:'postHttp',
styleUrls: ['./postHttp.scss'],
templateUrl: './postHttp.html',
})

export class GetHttpComponent implements OnInit{

...
constructor(private productService: ProductService) { }
...
postProduct(id: number): void {
this.productService.postProduct(id)
.subscribe(
(product: IProduct) => this.onProductRetrieved(product),
// ---> Instead of this (data:any)=>{ if(data.success){ //true } else { //false }}
(error: any) => this.errorMessage= <any>error
);
}

@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
createProduct(product: IProduct): Observable<IProduct> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});
letoptions = newRequestOptions({ headers: headers });
return this.http.post(this.baseUrl, product, options)
.map(this.extractData).catch(this.handleError);
}
}
}

postProduct.service.ts
----------------------
...
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
...
@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
createProduct(product: IProduct): Observable<IProduct> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});            
letoptions = newRequestOptions({ headers: headers });
return this.http.post(this.baseUrl, product, options)
.map(this.extractData);
}
}

private extractData(res: Response) {
    let body = res
    return body || {} ;
  }
   private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    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);
  }

react19-gh-pages: Github Actions

 Here's a polished LinkedIn post based on your content: 🚀 Deploy Your React 19 + Vite App to GitHub Pages in Minutes! Want to host your...