Setup Angular 2 Nodejs Structure – Angular CLI – Express

Angular 2 js is finally released after rolling up from all development phases, Alpha, Beta and release candidates. And Now we can code with the stable version. I was frequently going through Angular 2 and has worked with all previous version of Angular Beta and Release Candidate updates with some of my demo project ready. As Angular 2 is finally released, one of my Client asked me to start up an ecommerce based project with Angular 2 and nodejs. As I am soon going to initialize the project work, the first basic step for me to know about about how to integrate and setup Angular 2 Nodejs project structure and to make client Angular communicate with Server Nodejs Setup.

Setup Angular 2 Nodejs Structure - Angular CLI - Express
Setup Angular 2 Nodejs Structure – Angular CLI – Express

I used to play with Angular 2 code in my free time to create some demo, which also excites me to share my Angular 2 code with my team. As Angular 2 is very new and my team used to code with Angularjs 1 which is quite different to Angular 2, I engaged myself and two more coders of my team full time to work on this (angular 2 nodejs ecommerce based) project, so that me and both of my coders can learn, understand and accomplish the project within time constraint maintaining quality.

Lets give me a try to explain you how we can setup Angular 2 Nodejs Structure. Before getting into project structure, I am assuming that you would be aware of Angular 2 basics(components, routes, services, etc) and Nodejs (I am using Express Framework here).

prerequisites:

If you have not installed Angular CLI then you need to install it before going through this tutorial i.e by running


npm install -g angular-cli

OR

npm install -g angular-cli@latest

Note: Both the Angular CLI and generated project have dependencies that require Node 4 or higher, together with NPM 3 or higher.

Setup Angular 2 Nodejs Structure – Angular CLI – Express

Lets first create a Project folder at your desired location i.e I am creating folder name as nodejs-angular2-setup 


mkdir nodejs-angular2-setup

Make a directory, lets called it as client inside your project folder i.e nodejs-angular2-setup, where we are going to store all angular 2 code. You don’t need to use mkdir command, instead we can use Angular CLI to create a client generated code i.e


ng new client

Make sure you have already installed angular cli latest version. Now lets navigate to client and run and build angular 2 code i.e


cd client

ng build

ng serve 

You may check the output of Angular 2 code at http://localhost:4200. This way your client Angular 2 setup work is completed.

Secondly, also check if you can see generated files in dist folder inside client directory (this files were generated by ng build command). Now we are going to use this generated ‘dist folder’ and render this angular generated html javascript over nodejs port. Dist folder contains combined bundle html and javascript file which is finally used as your client data.

Coming back to parent folder i.e node-angular2-setup in your command line console to create a structure for server nodejs.

Lets first create a directory called as server inside main project and navigate to server directory.

Lets run init command, which would create a package.json file i.e


npm init

And provide input as required i.e Name, version, description etc for app as can be seen in the image provided below.

Setup Angular 2 Nodejs Structure - Angular CLI - Express
Setup Angular 2 Nodejs Structure – Angular CLI – Express

In the console, check if you are at server folder, and type in to install and initialize express.


npm install express --save

Now lets create a file app.js insider server and paste in following code.


var express = require('express');
var app = express();
var path = require('path');

app.use('/',express.static(__dirname+'/../client/dist'));

app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname+'/../client/dist','index.html'))
});

app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

app.listen(3000, function () {
console.log('Example listening on port 3000!');
});

module.exports = app; 

Finally your app structure would look like this:

Setup Angular 2 Nodejs Structure - Angular CLI - Express
Setup Angular 2 Nodejs Structure – Angular CLI – Express

You might be aware of the above code. We are just asking nodejs to serve static content from the dist folder of client i.e generated by angular 2. In this way when we will start the node express application, angular 2 code should serve the html and javascript content.

Finally start the server, and check if angular2 code is served on port 3000 (you may change the port number by defining in app.js). For starting nodejs server, just navigate to project home directory, and run following command from console.


node server/app.js

If you enjoyed and understand the article do share this post with your friends and collegaes. Also Do subscribe this blog to get the latest updated version of all upcoming post of Angular 2 js and nodjes.

Debug JavaScript code – Google chrome debugger help you

Debug JavaScript code with Google chrome. Debugging is a process of finding and reducing the number of bugs of your programs. As web developer are very much engaged coding with JavaScript, they need to frequently debug the code when the desired output does not comes. JavaScript code can be debugged easily in chrome or other browsers like internet explorer, Mozilla Firefox and many other list of browsers that are made just to debug JavaScript code. Google chrome provides this feature of debugging JavaScript code, and i used to explore bugs mostly in chrome only.

From here you can start over. Firstly install google chrome, and run your web app in chrome, which you want to debug. You can run the debugger, by selecting, options -> tools -> JavaScript console as seen in figure below:

Debug JavaScript code
Open debugger : Debug JavaScript code

Script tab will be opened. Usually, in the right side of the opened tab, you can see some of the important buttons to use debugger efficiently, whose description along with the image is given below:

Debug JavaScript code with Google chrome
Debug JavaScript code with Google chrome

Debug JavaScript code :

Here is the explanation of all buttons whose respective numbers are marked in the figure:

1. ) Play and pause : It is used if you want to debug the code or not.
2.) Step over : This button will make you jump step by step in your javascipt code
3.) Step into : This will cause the debugger to move its execution to the first line in the functions definition.
4.) Step out : This will cause debugger to move its execution to the parent function.
5.) deactivate breakpoints: This will remove all the breakpoints you have marked in the code.
6.) Breakpoints : Just put the cursor to the left of the code and the breakpoints will be marked.

Let me demonstrate you to debug very simple code given below. Here i had introduced an error, i.e written document.wrte instead of document.write in the code given below to print “Take care”. Here is the code. I have marked the error with the underline.:

Debug JavaScript code with Google chrome

<html>
<head>
<script type = “text/javascript”>
function call(){
document.write(‘Hello World!’);
document.wrte(‘Take care’);
}
</script>
</head>
<body>
Hello world
Call funtion : <input type=“button” value =“submit” onclick=“call()”>
This is my way.
</body>
</html>

Run the web page. Now to debug the code, open javascript console as described above, and see the error after pushing submit button.

Output of Debug JavaScript code with Google chrome

debug javascipt code with google chrome
Output : debug JavaScript code

It will indicate, that html document has no method wrte. Great, we caught the error, now modify the code, i.e instead of wrte correct it to write. Now run the code and jump to JavaScript console, your code is correct, no JavaScript error is found, as can be seen below:

debug javascipt code with google chrome
Ouput after correcting: debug JavaScript code

In the demo above, i have not used breakpoints, while you can mark breakpoints and debug it step by step with the tools provided in Google chrome.

CSS z-index – Overlap html element with different depth

CSS z-index – Overlap html element with different depth. z-index is one of the important css element, which concerns with the layers layout of a web page. Here Layer can be defined as a single thickness of some element covering a surface. If you put one layer above another, then the below layer would be hidden by the above layer. Z-index is also based on this concept. Or you can also compare x,y and z coordinates, where x and y represent plane and z indicates the depth. In other words it determines the stack level of HTML element. But remember, z-index works only when you define the position of that element i.e position as relative, absolute or fixed.

CSS z-index - Overlap html element with different depth
CSS z-index – Overlap html element with different depth

z-index is supported by all major browsers. z-index take positive value. The more the positive value is, means, that element will hide or overlap with the other elements of html. Here is the syntax of declaring z-index in css sytle sheet.

#zvalue{
	z-index : 1;
	position : absolute;
}

where zvalue is an id of one of the html element.
Let us have an example of putting a static html label text over an image. Here is the html code for the same:

CSS z-index – Overlap html element with different depth

<html>
<head>
<title>
css z index
</title>
</head>
<body>

<div id="image" style=" z-index: 1; position: relative;">
	<img src="css z-index.png" alt="z-index" >
</div>

<div id="label" style="margin: -133px 0px 0px 50px; z-index: 1; font-size: 40px; position: fixed;">
	z - index
</div>

</body>
</html>

Output of CSS z-index – Overlap html element with different depth

case 1 : For the above written code –

CSS z-index - Overlap html element with different depth
CSS z-index – Overlap html element with different depth

case 2 : If we will change the style value of id=”label” with z-index:2

CSS z-index - Overlap html element with different depth
CSS z-index – Overlap html element with different depth

Hope this helps to uplift one element over other in CSS with z-index. If you find any problem, then do comment below.

Open multiple page or tab with single link in html

Open multiple page or tab with single link in html. Many times you may require to open multiple pages if you want to give related and dependent information. Even now a days many website are opening multiple pages with single link to display advertisement too. You can directly use hyper link text with some tag to implement this.

We can provide a link in our web page to move directly to another page by <a href> tag. 

<a href=”http://www.javascripthtml.com”>your text to appear as link</a>

Which will appear as : your text to appear as link

But here you require to open up a multiple pages or tab with single link,  for giving additional information, and making your clients to come across the content that you want to make them read once. Here is the way:

Open multiple page or tab with single link in html
Open multiple page or tab with single link in html

Open multiple page or tab with single link in html

To Open multiple tabs or window with a single link, write the below written code in your html body.

Let us have an example to Open multiple page with single link in html, we would open following three pages:

  1.  Javascript i.e : http://www.javascripthtml.com/category/javascript/
  2. Angularjs : http://www.javascripthtml.com/category/javascript/angularjs/
  3. Html : http://www.javascripthtml.com/category/html/

By adding onclick event and window.open property in <a href> tag, you can open multiple page. Here is the example to do this:

<a onclick="window.open('http://www.javascripthtml.com/category/javascript/'); window.open('http://www.javascripthtml.com/category/javascript/angularjs/')" href="http://www.javascripthtml.com/category/html/" target="_blank">JavaScript HTML related links </a>

Output of Open multiple page or tab with single link in html:

JavaScript HTML related links

For Internet explorer this code will open multiple new windows, while for Google chrome and Mozilla Firefox it will open new tabs. You must allow browser to open popup for this website, while testing.

I hope that the above post will make your work easy to open multiple pages with click on single link. Do comment for your feedback, problems and valuable suggestion

How to add scroll bar in HTML CSS

How to add scroll bar in HTML CSS. While writing a post sometimes we require a line to appear without any break, more than the provided width of the post and sometimes we do not want to exceed the height of the post with all the content appear in the blog. Here we require scroll bar box. You can add horizontal scroll bar in a box or vertical or both horizontal or vertical scroll bar to function in a box with help of overflow element.

How to add scroll bar in html
How to add scroll bar in html

How to add scroll bar in HTML CSS

Adding a  vertical scroll in a box :

Here is the html code :

<div style=”height:100px; width:550px; overflow-y: scroll; padding-bottom:10px; border:3px solid black; “>
<pre>

your text

</pre>
</div>

which will look as :

html code to put scroll box appear in the post :

vertical scroll box

horizontal scroll box

both vertical and horizontal scroll box

 

Adding a horizontal scroll in a box :

Here is the html code :
<div style=”height:200px; width:550px; overflow-x: scroll; padding-bottom:10px; border:3px solid black; “>
<pre>

put your text here

</pre>
</div>

Which will look as :

html code to put scroll box appear in the post :vertical scroll box

horizontal scroll box

both vertical and horizontal scroll box

Adding both horizontal and vertical scroll box :

html code is  :

<div style=”height:200px; width:550px; overflow-x: scroll; overflow-y: scroll padding-bottom:10px; border:3px solid black; “>
<pre>

put your text here

</pre>
</div>

Which will look as :

html code to put scroll box appear in the post :

   vertical scroll box

     horizontal scroll box

       both vertical and horizontal scroll box

You can configure your box with the attributes like, set the font style, font size, color of fonts, background color of the box, border style etc.

For example :

html code to put scroll box appear in the post :

   vertical scroll box

     horizontal scroll box

       both vertical and horizontal scroll box

For the box above html code is :

<div style=”width: 550px; height: 200px; color: 000000; background-color: #DC143C; font-family: arial; font-size: 12px; text-align: left; border: 2px dashed 000000; overflow:scroll; padding: 4px;”>
<pre>

put your text here

</pre>
</div>

If you have any problem related to code of How to add scroll bar in HTML CSS, ask by writing comment on the below space provided. We will work on that. Your valuable suggestion and feedback are always welcomed.

Load Dynamically JavaScript file in AngularJs with RequireJs

Load Dynamically JavaScript file in AngularJs with RequireJs . If you are creating larger scale apps, where you need to deal with separate defined controllers, services and directives in different files which are required to get loaded for performing some part of functions. So it would be best practice to load controllers or services JavaScript file dynamically when required instead of loading all bunch of file at single hit, which might result in increasing latency time of response of page. Well this could be easily achieved with the help of RequireJs, where we just need to set and call required files, while the rest RequireJs would worry to do the importing.

Load Dynamically JavaScript file in AngularJs with RequireJs
Load Dynamically JavaScript file in AngularJs with RequireJs

As at this moment, I am also new to AngularJs, so I need to searched for the solution, for how to load JavaScript file dynamically in AngularJs, all around the Google. And now I am up with the perfect and simplest solution. With the help of AngularAMD and requirejs, allows you to build AMD (asynchronous module definition) modules, within some minutes.

“angularAMD is an utility that facilitates the use of RequireJS in AngularJS applications supporting on-demand loading of 3rd party modules such as angular-ui.” – Marcos Lin

Example – Load Dynamically JavaScript file in AngularJs with RequireJs

Here is the sample and description to load modules Dynamically in AngularJs projects. Requirement:
angularAMD.js
require.js
angular-route.js

Lets take a simple converter application, which will facilitates conversion of temperature and length, where temperature controller and length controller modules is defined in separate files. Now our target is to load temperature or length controller file, when required.

Firstly create boot.js, which will be loaded initially, where we will define modules path, shim and dependency. Here is how boot.js looks like:

In boot.js:

require.config({
    baseUrl: "js",
    paths: {
        //defining the variables to the path of resepective js files present in the project foler.
        angular: "../lib/angular.min",      
        "angular-route": "../lib/angular-route.min",
        angularAMD: "../lib/angularAMD"
    },
    shim: {
        //as requirejs follows AMD, so shim confirms the loading of dependent file in sequence.
        //here angularAMD and angular-route is dependent on angular, so angular is loaded before the two
        angularAMD: ["angular"],
        "angular-route": ["angular"]
    },
    //deps will execute app.js
    deps: ["app"]
});

In app.js

define(["angularAMD", "angular-route"], function(angularAMD) {
    var app = angular.module("webapp", ["ngRoute"]);    
    app.config(function($routeProvider) {
        $routeProvider
        .when("/", angularAMD.route({
            templateUrl: "template/home.html",
            controller: "HomeCtrl",
            //if all controller javascript file is defined in boot.js file,
            //there is no need to define controllerUrl in any of the case.
            controllerUrl: "js/HomeCtrl.js"
        }))
        .when("/temperature", angularAMD.route({
            templateUrl: "template/View.html",
            controller: "TemperatureController",
            controllerUrl: "js/TemperatureCtrl.js"
        }))
        .when("/length", angularAMD.route({
            templateUrl: "template/View.html",
            controller: "LengthController",
            controllerUrl: "js/LengthCtrl.js"
        }))
        .otherwise({
            redirectTo: "/"
        })
    });

    //this will bootstrap the application. There is no need to define 'ng-app' in HTML file
    return angularAMD.bootstrap(app);
});

In index.html:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="css/style.css">
    <!-- data-main define the entry point for RequireJS configuration-->
    <script data-main="js/boot.js" src="lib/require.js"></script>
  </head>
  <body>
    <div ng-view></div>
  </body>
</html>

In View.html

<h1><a href="#/">Home</a></h1>

<div id="inputElem">{{fromUnit}} <input class="item item-input" type="number" placeholder="0" step="0.01" ng-model="data" ng-change="getValue(data)"></div>

<div id ="rowvalue" class="row" ng-repeat="(key,value) in result">
	<div id="colvalue" class="col-sm-6">{{key}} : {{value}}</div>
</div>

In HomeCtrl.js

define(["app"],function(app){
	app.controller("HomeCtrl",function($scope){
		console.log("home controller is loaded");
})
});

In TemperatureCtrl.js

define(["app"],function(app){
    app.controller('TemperatureController', function($scope) {	
    	$scope.fromUnit = "CELSIUS";
		$scope.result = {'CELSIUS': '0', 'KELVIN':'0', 'FAHRENHEIT' : '0'};
		
                  $scope.getValue = function(temp){
			Fahrenheit = (temp * 9 / 5) + 32;
			Kelvin = temp*1.0 + 273.15;
			Celsius = temp;
			$scope.result = {'CELSIUS':Celsius, 'KELVIN':Kelvin, 'FAHRENHEIT' : Fahrenheit};
		};
	})
});

In LengthCtrl.js

define(["app"],function(app){
    app.controller('LengthController', function($scope) {	
    	$scope.fromUnit = "CENTIMETER";
		$scope.result = {'CENTIMETER':'0', 'METER':'0','INCH':'0'};
		 
                 $scope.getValue = function(temp){
			var cm = temp;
			var m = 0.01 * temp;
			var inch = 0.393700787401575 * temp; 
			$scope.result = {'CENTIMETER':cm, 'METER':m,'INCH':inch};
		};
	})
});

Here is the working demo of the above given code:

Demo : Load Dynamically JavaScript file in AngularJs with RequireJs

If you want to test for dynamically loading of JavaScript, open up Network tab of your browser and see how files get loaded when the page is called. If you are getting any difficulty, do comment below, we would try to resolve it. Also do share if you have another solution for the same.

Simple Html Calculator – code program

Html Calculator – code program. This post is made to make a html calculator, which works on browser. A form is made whose name is assigned as calculator. The name attribute specifies the name of a form. Input type are included in the code for a form, which makes, ‘textfield’ and ‘button’. Every input field is specified with attribute value. The value attribute specifies the value of an <input> element. Eval() function, takes the expression and evaluates accordingly. On click’ is the event. It occurs when  the user clicks on an element. This is how the following below code is write to make html calculator.

Html Calculator
Html Calculator

Html Calculator – code program

<html>
<head>
    <title>Html calculator</title>
</head>
<body>
    <form name="calculator" >
    Solution<input type="textfield" name="ans" value="">
    <br>
    <input type="button" value="1" onClick="document.calculator.ans.value+='1'">
    <input type="button" value="2" onClick="document.calculator.ans.value+='2'">
    <input type="button" value="3" onClick="document.calculator.ans.value+='3'">
    <input type="button" value="+" onClick="document.calculator.ans.value+='+'">
    <br>
    <input type="button" value="4" onClick="document.calculator.ans.value+='4'">
    <input type="button" value="5" onClick="document.calculator.ans.value+='5'">
    <input type="button" value="6" onClick="document.calculator.ans.value+='6'">
    <input type="button" value="-" onClick="document.calculator.ans.value+='-'">
    <br>
    <input type="button" value="7" onClick="document.calculator.ans.value+='7'">
    <input type="button" value="8" onClick="document.calculator.ans.value+='8'">
    <input type="button" value="9" onClick="document.calculator.ans.value+='9'">
    <input type="button" value="*" onClick="document.calculator.ans.value+='*'">
    <br>
    <input type="button" value="0" onClick="document.calculator.ans.value+='0'">
    <input type="reset" value="Reset">
    <input type="button" value="=" onClick="document.calculator.ans.value=eval(document.calculator.ans.value)">
    </form>
    </body>
</html>

Output of Html Calculator – code program

Solution








Html Table – code program example

Html Table – Table is two dimension structure, with rows and columns making collection of cells, in which we can display our data.

Html Table
Html Table

To create Html Table in website or blog, “table” tag is used to display or create html table as shown below :

Html Table – code program example

<table border="1">
<tr>
<th>Name</th>
<th>Post</th>
<th>Salary</th>
</tr>
<tr>
<td>Geeta</td>
<td>Manager</td>
<td>20000</td>
</tr>

<tr>
<td>Ravi/td>
<td>clerk</td>
<td>5000</td>
</tr>
<tr>
<td>Mohan</td>
<td>clerk</td>
<td>5000</td>
</tr>
<tr>
<td>Shyam</td>
<td>Clerk</td>
<td>5000</td>
</tr>
</table>

Output of Html Table – code program example:

Name Post Salary
Geeta Manager 20000
Ravi/td> clerk 5000
Mohan clerk 5000
Shyam Clerk 5000

<table> tag

This tag is used to create table.

<border>tag :

Border is an attribute of tag table which is used to display the border lines of table and its values is defined in pixels.

<tr> tag :

“tr” tag is used to introduce or create a row. Row tag is closed after the end of row.

<th> tag :

“th” is used to write the data in heading format, i.e written in bold letters.

<td> tag :

“td” is used to insert data

Subscript and Superscript code in Html

Subscript and Superscript code in Html. How to write subscript and superscript in blog-post using html code.

Subscript and Superscript code in Html

Subscript and Superscript code in Html
Subscript and Superscript code in Html

Html Subscript

A Html subscript is a symbol which appear smaller than the normal size and is written just below the text line, as shown below:

H2O

Below is the html Subscript code to put Subscript in your website or post

Text – “sub” is the tag to make subscript

eg of Html Subscript:
H<sub>2</sub>O  will make output

as H2O

Html superscript

A Html superscript is a symbol which appear smaller than the normal size and is written slightly above the text line, as shown below:

1st

below is the html code to put superscript in your website or blog post

For superscript – : your text – “sup” is the tag to make superscript

eg:
1<sup>st</sup> will make output as 1st

How to make superscript and subscript appear simultaneously

To make both appear, i.e Subscript and Superscript code in Html:

<sup>1<sub>1</sub></sup>H which will output as 11H

Html link on image map

Html link on image map.  Html image may be link by either two ways, i.e 1st, you can link the whole image with one link, or an html image can take more take one link, with different area or regions of an image will have different link. In this post you will be explained both the techniques, but to understand the later one, do read these post : html image multiple link. Here are the techniques:

1. Single Html link on image map

Enclose the image tag by hyperlink tag i.e with ‘<a href>’ tag, similarly as you write in making a text hyperlink. With this the whole image will become clickable
Here is the example to write the syntax:
<a href = “www.example.com” ><img src=”image.png” alt=”image”/></a>

For example here is the code and example of the same :

<html>
<head>
    <title>
    Html link on image map
    </title>
<body>
    <a href="http://www.cprogramto.com">
        <img src="image2.png" alt ="Html link on image map"/>
    </a>
</body>
</html>
html link on image map
html link on image map

2. Multiple Html link on image map

You need to define ‘usemap’ attribute in <img> tag, and then define that map, with different area with different link.

Syntax:
<img src=”imageExample.png” alt=”html link on image” usemap=”#nameOfMap”>

Then define map tag, with different areas and different hyper link.

<map name=”nameOfMap”>
<area href=”” shape=”rect” coords=”0,0,160,160″ alt=”alt tag”>
<area href=”” shape=”circle” coords=”180,100,4″ alt=”alt tag”>
</map>

Here is the example with code for multiple html link on an image:

<html>
<head>
</head>
<body>
<img alt="image" usemap="#mapping" src="image.png">
<map name="mapping">
	<area shape="rect" coords="40,40,180,163" href="http://www.cprogramto.com/c-program-example/">
	<area shape="circle" coords="330,100,77" href="http://www.cprogramto.com/category/java/">
</map>
</body>
</html>