Saturday, 17 February 2018

NG5- Event Bubling

NG5- Event Bubling
-------------------------
DOM events provide a mechanism that can prevent bubbling. It is the stopPropagation method. 
@Component({
  selector: 'event-bubbling',
  template: `
    <div>
      <button (click)="onClick($event, 'Button 1')">Button 1</button>
      <button (click)="onClick($event, 'Button 2')">Button 2</button>
    </div>
  `
})
export class EventBubblingComponent {
  @Output() click = new EventEmitter();

  onClick(event: Event, button: string) {
    event.stopPropagation();

    this.click.next(button);
  }
}

E.g
----
<div (click)="hidetheDiv()"> <span (click)="maketheFunctionCall($event,item)"> API Call </span>  Close X</div>

  
  maketheFunctionCall(event:Event,item){
    event.stopPropagation();
    console.log("Make the API call", item)
  }
  
  hidetheDiv(){
  this.Div = false;
  }

Thursday, 1 February 2018

NG5- Module - App.module.ts

NG5- Module - App.module.ts
========================

=>Angular apps are modular and Angular has its own modularity system called NgModules. NgModules are a big deal.

=>Every Angular app has at least one NgModule class, the root module, conventionally named AppModule.
=>While the root module may be the only module in a small application, most apps have many more feature modules, each a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities.

->An NgModule, whether a root or feature, is a class with an @NgModule decorato
NgModule is a decorator function that takes a single metadata object whose properties describe the module. The most important properties are:

->declarations - the view classes that belong to this module. Angular has three kinds of view classes: components, directives, and pipes.

->exports - the subset of declarations that should be visible and usable in the component templates of other modules.

->imports - other modules whose exported classes are needed by component templates declared in this module.

->providers - creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app.

->bootstrap - the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property

generic.app.module.ts
---------------------

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  imports:      [ BrowserModule ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }


Sample Ng-cli app.module at initial level
--------------------------------------------

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// import { routing } from './app.routing.ts';  =>  App routing file needs to include 
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [ // import Angular's modules ->BrowserModule,    HttpModule,    RouterModule,    FormsModule,    ReactiveFormsModule, <= coresponding import statement as to add 
BrowserModule   
  ],
  providers: [],   // expose our Services and Providers into Angular's dependency injection  Mostly service files <= coresponding import statement as to add 
  bootstrap: [AppComponent]
})
export class AppModule { }

NG5- angular-cli change port to 3000 in angular-cli.json

NG5- angular-cli change port to 3000 in angular-cli.json or ng serve --port 3000 cmd
==========================================================

soln:1
--------

Edit with Angular-CLI 1.0.0

You can now directly define the used port in the .angular-cli.json file by defining the property like this:

{
    "defaults": {
"styleExt": "scss",
"component": {},
        "serve": {
            "port": 3000
        }
    }
}
Here is a direct link to all available options for the configuration: Angular-CLI options configuration

Soln:2
-------
Old Answer

You can configure it directly in your packages.json, change your start scripts by:

"start": "ng serve --port 2500",
And then run your server with npm start


this will override the .angular.cli.json file. app will run in 2500 port.


Soln:3
------
You can also try with this to run your application in visual studio code -:

ng serve --open --port 4201

you can give any port number. 

*** It will in open in default browser. e.g I.E edge in windows or your preferred browser.

Ref: https://stackoverflow.com/questions/41260194/angular-cli-change-port-to-3000-in-angular-cli-json

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>

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