Wednesday, 31 January 2018

NG4-router - 2 way to implement. 1.routing within module file, 2. routing file as separate

NG4-router  - 2 way to implement. 1.routing within module file, 2. routing file as separate
===========

router we can achieve based on url change.

Method:1
--------
Write the routing in Module file it self. No need to import or create mycompoent.routing.ts file externally.
Most important = We can achieve Lazy loading using ForChild(routes)

app.module.ts
-------------
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Component1Module } from './modules/my-Componet1/Componet1.module';
import { service } from './modules/Serivice';


@NgModule({
  bootstrap: [App],
  declarations: [   App, RedirectPage   ],
 
  imports: [ // import Angular's modules
    BrowserModule,
    HttpModule,
    RouterModule,
    MyComponet1Module
],
  providers: [ // expose our Services and Providers into Angular's dependency injection
Service,
  ]
})

export class AppModule {

  constructor() {
  }
}


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

<main >
 <nav>
  <a routerLink='/first-component' >HTML</a> |
  <a routerLink='/Second-Component' >CSS</a> |
  </nav>
  <router-outlet></router-outlet>
</main>


Component1.module.ts
--------------------


const routes: Routes = [
  {
    path: 'first-component',
    component: Component1.component
  }
]
const routing = RouterModule.forChild(routes);

@NgModule({
  imports: [],
  declarations: [Component1Component],
   providers: []
   })

export class component1Module { }

Component1.Component.ts
-----------------------
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'compare',
  templateUrl: './Component1.html',
  styleUrls: ['./Component1.scss']
})
export class Component1Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }
 }


Component1.html
---------------
component1 Content comes Here...



Method:2
--------
create a Routing file for every separate module and do the routing wiht routes { path: '/compnent2, component:}
How to include multiple component into major component and display - dashboard (aggr and charts )

Same the app.module.ts , app.component.ts and app.compnent.html


Component2.module.ts
--------------------
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { routing } from './my-reports.routing';

@NgModule({
  imports: [ routing ],     // here we import routing from external routing file.
  declarations: [Component2Component],
  providers: []
   })

export class component2Module { }

Component2.routing.ts
----------------------
import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import { MyReportsComponent } from './my-reports.component';

const routes: Routes = [
  {
    path: 'Second-Component',
    component: MyReportsComponent
  }
]

export const routing: ModuleWithProviders = RouterModule.forChild(routes);


Component2.Component.ts
-----------------------
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'compare2',
  templateUrl: './Component2.html',
  styleUrls: ['./Component2.scss']
})
export class Component2Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }
 }


Component2.html
---------------
component2 Content comes Here...


Tuesday, 30 January 2018

Ng4- Apply Css ngClass (attribute directive) based on more than one condition( && ||)

Ng4- Apply Css ngClass (attribute directive) based on more than one condition( && ||)
===========================================================
Use case:1
----------
you can't directly use <div [ngClass]="{'cssClass1': value1 && value2,'cssClass2': value1 || value2 }"} Css effect in Template </div>
firefox browser doesn't support the && perfectly.
Use case:
----------
more than 2 condition check in with css ngClass make performance better via component function
<div [ngClass]="{'cssClass1': value1,'cssClass2': value2, 'cssClass3':value3}"} Css effect in Template </div>

Solution:
----------
Component.template.html
------------------------
<div [ngClass]="{'cssClass1': isCondtionTrue(),'cssClass2': isvalid() }"} Css effect in Template </div>

Component.component.ts
----------------------
import { component } from '@angular/component';
import { } from '@angular/route';

@Component({
  selector: 'ngClassFunction',
  templateUrl: './Component.template.html',
  styleUrls: ['./Component.template.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ComponentComponent implements OnInit, OnChanges {

constructor(){
}
isCondtionTrue(){
if(this.value1 && this.value2)
return true;
else false;
}
isvalid(){
if(this.value1 && this.value2)
return true;
else false;
}

}

NG4- AOT Build failed due to Javascript Heap Out of Memory

NG4- AOT Build failed due to Javascript Heap Out of Memory 
=============================================

It will occur build memory space is less to build our Angular 2 code.
Here we are forcing to increase memory space to build.

Many thanks! Working perfectly with
node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng serve --aot
Or for build
node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng build -prod


Ref: https://github.com/angular/angular/issues/20687

Friday, 29 December 2017

Node JS - EJS Effective JavaScript templating <% = EJS %>


what is EJS 
EJS Effective JavaScript template
E" is for "effective." EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.
 No religiousness about how to organize things. No reinvention of iteration and control-flow. It's just plain JavaScript.

Features
=========
Fast compilation and rendering
Simple template tags: <% %>
Custom delimiters (e.g., use <? ?> instead of <% %>)
Includes
Both server JS and browser support
Static caching of intermediate JavaScript
Static caching of templates
Complies with the Express view system

Installation:
============
It's easy to install EJS with NPM.
$ npm install ejs

e.g:
=====
var ejs = require('ejs'),
    people = ['geddy', 'neil', 'alex'],
    html = ejs.render('<%= people.join(", "); %>', {people: people});

Tags:
====
<% 'Scriptlet' tag, for control-flow, no output
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline

custom Delimeters:
------------------
Custom delimiters can be applied on a per-template basis, or globally:

var ejs = require('ejs'),
    users = ['geddy', 'neil', 'alex'];

// Just one template
ejs.render('<?= users.join(" | "); ?>', {users: users},
    {delimiter: '?'});
// => 'geddy | neil | alex'

// Or globally
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});

Ref: http://ejs.co/

Thursday, 28 December 2017

NodeJs - Nodemon - reload , automatically


Nodemon is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. Install it using npm.


Just use nodemon instead of node to run your code, and now your process will automatically restart when your code changes. To install, get node.js, then from your terminal run:



npm install -g nodemon

Features:
-----------

Automatic restarting of application.

Detects default file extension to monitor.
Default support for node & coffeescript, but easy to run any executable (such as python, make, etc).
Ignoring specific files or directories.
Watch specific directories.
Works with server applications or one time run utilities and REPLs.
Requirable in node apps.
Open source and available on github.

REf: https://nodemon.io/

Sunday, 27 August 2017

JS - Date functions and Date -Formats

<script type="text/javascript">
//date funciton
getFullYear() - Retrun -full year ( all 4 digits)
getMonth() - return 0-11
getDate() - retrun 1-31
getDay() - return ( 0-6 , 0-is sunday)
getHours()- return 0-23
getMinuts() - return 0-59
getSeconds - return 0-59
getMilliseconds() - retrun 0-9999


function dateFormat(){

var d= new Date();
var yyyy = d.getFullYear();

var month = d.getMonth();
if(month <10){
month = "0"+month;
}

var day = d.getDate();
if(day < 10){
day = "0"+day;
}

console.log( day + '/' + month + '/' +yyyy )

}
dateFormat();
</script>

JS - Error Handling - Try throw catch finally

<script type="text/javascript">

var numerator = Number(prompt("enter numerator"));
 var denominator = Number(prompt("enter denominator")); 



 try { 
if( denominator == 0){ 
throw{
error: "divided by 0",
message: " customize error msg "
}
}
else {
document.write("REsult is "+ (numerator/denominator));
}

 }
 catch (e){
console.log(e) // [Object object]
console.log(e.error, e.message)  // custome Error Message 
 }
 finally
{
// if there is exception or not finally block will execute
console.log("finally block");
}


</script>

JS - Array - push ===unshift or pop === shift

push the value to end of an array element, unshift push the element at beging of array
pop remove the last element of an array, shift remove the first element of an array. 

<script type="text/javascript">

var myArr = [2,3];
document.write("Orginal Arr "+myArr+"<br>")
myArr.push(4);
myArr.unshift(1)
document.write("unshift 1 and push 4 "+myArr+"<br>")

myArr.pop();
myArr.shift();
document.write("shift and pop "+ myArr+"<br>")

document.write(myArr.length)
</script>

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


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...