Wednesday 15 June 2016

Angular 2 - Learn from Scratch

Your first Angular 2 app

Download the seed project and extract it somewhere on your machine. Inside this project, you’ll find a few  configuration files, an index.html and an app folder, which includes the source files for our application.
Inside the app folder, we have a couple of TypeScript files: boot.ts, which is the main or starting module of our application, and app.component.ts, which is the root componentof our application. Every Angular 2 app has at least one component, which we call root component.
tsconfig.json is the configuration file TypeScript compiler uses to determine how to transpile our TypeScript code into Javascript.
typings.json is another configuration file for Typescript. When using external Javascript libraries in TypeScript, we need to import a typescript definition file. A type definition file gives us static type checking and IntelliSense for that Javascript library.
Next to that, we have package.json, which is a standard Node package configuration file, where we define the dependencies of our app.

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  },  
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.7",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.5.15"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.7.5"
  }
}

Now, we need to install these dependencies. So, open up Command Prompt on Windows or Terminal on Mac, and go to the folder where you’ve extracted the seed project. Then, run:

npm install 

This is going to take several minutes for the first time, so be patient. If you get several errors, that’s most likely due to administrative privileges. So, on Mac, be sure to add sudo before npm. 
Once these dependencies are installed, you’ll see a new folder called node_modules. All our application dependencies will be stored there.
Now, have one more look at package.json. Under the scripts section, we can have a few custom node commands:

"scripts": {
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
  }

The one we’ll be using a lot is start.

    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",  

 
It’s a shortcut for concurrently running two commands:
  • npm run tsc:w: which runs TypeScript compiler in the watch mode. When we save a TypeScript file, TypeScript compiler will automatically detect the changes and transpile our TypeScript code into Javascript. We never have to view or modify these Javascript files. So we code purely in TypeScript.
  • npm run lite: this will run the lite web server for our Angular app.
Now, back in the terminal and run the following command from the project folder:

npm start

When the lite web server starts, it’ll launch your default browser navigating tohttp://localhost:3000. This is our first Angular 2.0 app.
angular2-tutorial

What is a component?

A component is one of the most fundamental building blocks in Angular 2 apps. Every app consists of at least one component, which we call the root component. A component can include other components, which we call child components. A real-world app is essentially a tree of components.
But what are these components really? A component is a TypeScript class that encapsulates the template, data and behaviour for a view. So, it’s more accurate to call it a view component. That’s what they’re called in React.
As an example, think of Twitter. If you want to build a similar app in Angular 2, you may model your application components like this:
  • app
    • navbar
    • sidebar
    • content
      • tweets
        • tweet

Root component

Open up app/app.component.ts. This is the root component of our app:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>' 
}) 
export class AppComponent { }
As you see, a component is a TypeScript class decorated with @Component decorator. We use decorators (also called annotations) to add metadata to a class. This@Component decorator tells Angular that AppComponent is a component. Note that these decorators are actually functions. So, here, @Component is called and given an object which includes metadata about AppComponent:

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>' 
})
This object has two properties: template, which specifies the markup that should be rendered when this component is used, and selector, which tells Angular where in the DOM it should render this component. This is a CSS selector. So, my-app here represents an element with the name my-app.
When Angular sees an element like that in the DOM, it’ll create an instance ofAppComponent and render it (according to its template) inside that element. Open upindex.html and scroll down a bit. Note the my-app element.

Rendering data

Back in app.component.ts, let’s define a field in this class:

export class AppComponent { 
 title = "Hello World";
}

So, as I explained earlier, a component encapsulates the template, data and the behaviour for a view. We use fields to store data. Now, let’s render the value of this field in the template. Modify the template as follows:

    template: 'Hello {{title}}' 
We use double curly braces syntax, called interpolation, to render data.
Now, save the file. Since TypeScript compiler is running in the background, it will re-compile our AppComponent. Our lite web server uses a module called BrowserSync, which automatically refreshes the browser when it detects a change in the source files. So, if you switch back to your browser, you should see the new content.

Handling events

Let’s extend our component and add a button. First, replace the single quote character in the template with backtick. That’s the character to the left of number 1 on your keyboard. By using backtick, we can break up our template into multiple lines and make it more readable.

@Component({
    selector: 'my-app',
    template: `
<h1>Hello {{title}}</h1>
` 
})
Now, add a button and a span to the template:

<h1>Hello {{title}}</h1>
<span><span>
<button>Click me</button>
We want to display a counter on this view. Every time we click the button, the counter will be increased by one. So, first declare a new field in the component:

export class AppComponent { 
        count = 0;
        title = "Hello World";
}

Then, modify the span and use interpolation to render the value of count:

<span>Clicks: {{count}}<span>
Finally, to handle the click event, we need to bind it to a method in our component. When we click the button, the corresponding method in the component will be called.
Change the button declaration as follows:

<button (click)="increaseCount()">Click me</button>
Note the syntax. This is called event binding. So, we put the event name in parentheses and then set to a method in the component.
Now, let’s create this method:

export class AppComponent { 
 count = 0;
 title = "Hello World";

 increaseCount(){
  this.count++;
 }
}

Save the file and switch back to your browser. Click the button a few times and note the counter.
So, in this article, you learned the basics of components in Angular 2.0 apps. A component encapsulates the template, data and behaviour of a view. We used interpolation to render data and event binding to handle events raised from DOM elements.
In the next part, we’ll look at services and dependency injection. If you want to be notified when I publish the next part, subscribe to my blog below.

Saturday 15 August 2015

Hi All today will discuss with goodness of jquery and some best practices of writing codes in javascript and jquery:-

uRULE #1: SEPARATE JAVASCRIPT FUNCTIONALITY

Separate Javascript functionality into a “behavioural layer,” so that it is separate from and independent of (X)HTML and CSS. (X)HTML is the markup, CSS the presentation and Javascript the behavioural layer. This means storing ALL Javascript code in external script files and building pages that do not rely on Javascript to be usable.
For a demonstration, check out the following code snippets:
CrossBad markup:
Never include Javascript events as inline attributes. This practice should be completely wiped from your mind.
<a onclick="doSomething()" href="#">Click!</a>
TickGood markup:
All Javascript behaviours should be included in external script files and linked to the document with a <script> tag in the head of the page. So, the anchor tag would appear like this:
<a href="backuplink.html" class="doSomething">Click!</a>
And the Javascript inside the myscript.js file would contain something like this:
...

$('a.doSomething').click(function(){
 // Do something here!
 alert('You did something, woo hoo!');
});
...
The .click() method in jQuery allows us to easily attach a click event to the result(s) of our selector. So the code will select all of the <a> tags of class “doSomething” and attach a click event that will call the function. In practice, this
In Rule #2 there is a further demonstration of how a similar end can be achieved without inline Javascript code.

RULE #2: NEVER DEPEND ON JAVASCRIPT

To be truly unobtrusive, a developer should never rely on Javascript support to deliver content or information. It’s fine to use Javascript to enhance the information, make it prettier, or more interactive—but never assume the user’s browser will have Javascript enabled. This rule of thumb can in fact be applied to any third-party technology, such as Flash or Java. If it’s not built into every web browser (and always enabled), then be sure that the page is still completely accessible and usable without it.
CrossBad markup:
The following snippet shows Javascript that might be used to display a “Good morning” (or “afternoon”) message on a site, depending on the time of day. (Obviously this is a rudimentary example and would in fact probably be achieved in some server-side scripting language).
<script language="javascript">
var now = new Date();
if(now.getHours() < 12)
 document.write('Good Morning!');
else
 document.write('Good Afternoon!');
</script>
This inline script is bad because if the target browser has Javascript disabled, NOTHING will be rendered, leaving a gap in the page. This is NOT graceful degradation. The non-Javascript user is missing out on our welcome message.
TickGood markup:
A semantically correct and accessible way to implement this would require much simpler and more readable (X)HTML, like:
<p title="Good Day Message">Good Morning!</p>
By including the “title” attribute, this paragraph can be selected in jQuery using a selector (selectors are explained later in this article) like the one in the following Javascript snippet:
var now = new Date();
if(now.getHours() >= 12)
{
 var goodDay = $('p[title="Good Day Message"]');
 goodDay.text('Good Afternoon!');
}
The beauty here is that all the Javascript lives in an external script file and the page is rendered as standard (X)HTML, which means that if the Javascript isn’t run, the page is still 100% semantically pure (X)HTML—no Javascript cruft. The only problem would be that in the afternoon, the page would still say “Good morning.” However, this can be seen as an acceptable degradation.

RULE #3: SEMANTIC AND ACCESSIBLE MARKUP COMES FIRST

It is very important that the (X)HTML markup is semantically structured. (While it is outside the scope of this article to explain why, see the links below for further reading on semantic markup.) The general rule here is that if the page’s markup is semantically structured, it should follow that it is also accessible to a wide range of devices. This is not always true, though, but it is a good rule of thumb to get one started.
Semantic markup is important to unobtrusive DOM scripting because it shapes the path the developer will take to create the DOM scripted effect. The FIRST step in building any jQuery-enhanced widget into a page is to write the markup and make sure that the markup is semantic. Once this is achieved, the developer can then use jQuery to interact with the semantically correct markup (leaving an (X)HTML document that is clean and readable, and separating the behavioural layer).
CrossTerrible markup:
The following snippet shows a typical list of items and descriptions in a typical (and terribly UNsemantic) way.
<table>
    <tr>
        <td onclick="doSomething();">First Option</td>
        <td>First option description</td>
    </tr>
    <tr>
        <td onclick="doSomething();">Second Option</td>
        <td>Second option description</td>
    </tr>
</table>
CrossBad markup:
The following snippet shows a typical list of items and descriptions in a more semantic way. However, the inline Javascript is far from perfect.
<dl>
    <dt onclick="doSomething();">First Option</dt>
    <dd>First option description</dd>
    <dt onclick="doSomething();">Second Option</dt>
    <dd>Second option description</dd>
</dl>
TickGood markup:
This snippet shows how the above list should be marked up. Any interaction with Javascript would be attached at DOM load using jQuery, effectively removing all behavioural markup from the rendered (X)HTML.
<dl id="OptionList">
    <dt>First Option</dt>
    <dd>First option description</dd>
    <dt>Second Option</dt>
    <dd>Second option description</dd>
</dl>
The <id> of “OptionList” will enable us to target this particular definition list in jQuery using a selector—more on this later.

3. Understanding jQuery for Unobtrusive DOM Scripting

This section will explore three priceless tips and tricks for using jQuery to implement best practices and accessible effects.

UNDERSTANDING SELECTORS: THE BACKBONE OF JQUERY

The first step to unobtrusive DOM scripting (at least in jQuery and Prototype) is using selectors. Selectors can (amazingly) select an element out of the DOM tree so that it can be manipulated in some way.
If you’re familiar with CSS then you’ll understand selectors in jQuery; they’re almost the same thing and use almost the same syntax. jQuery provides a special utility function to select elements. It is called $.
A set of very simple examples of jQuery selectors:
$(document); // Activate jQuery for object
$('#mydiv')  // Element with ID "mydiv"
$('p.first') // P tags with class first.
$('p[title="Hello"]') // P tags with title "Hello"
$('p[title^="H"]') // P tags title starting with H
So, as the Javascript comments suggest:
  1. $(document);
    The first option will apply the jQuery library methods to a DOM object (in this case, the document object).
  2. $(‘#mydiv’)
    The second option will select every <div> that has the <id> attribute set to “mydiv”.
  3. $(‘p.first’)
    The third option will select all of the <p> tags with the class of “first”.
  4. $(‘p[title=”Hello”]’)
    This option will select from the page all <p> tags that have a title of “Hello”. Techniques like this enable the use of much more semantically correct (X)HTML markup, while still facilitating the DOM scripting required to create complex interactions.
  5. $(‘p[title^=”H”]’)
    This enables the selection of all of the <p> tags on the page that have a title that starts with the letter H.
These examples barely scratch the surface.
Almost anything you can do in CSS3 will work in jQuery, plus many more complicated selectors. The complete list of selectors is well documented on the jQuery Selectors documentation page. If you’re feeling super-geeky, you could also read the CSS3 selector specification from the W3C.

GET READY.
$(DOCUMENT).READY()

Traditionally Javascript events were attached to a document using an “onload” attribute in the <body> tag of the page. Forget this practice. Wipe it from your mind.
jQuery provides us with a special utility on the document object, called “ready”, allowing us to execute code ONLY after the DOM has completely finished loading. This is the key to unobtrusive DOM scripting, as it allows us to completely separate our Javascript code from our markup. Using $(document).ready(), we can queue up a series of events and have them execute after the DOM is initialized.
This means that we can create entire effects for our pages without changing the markup for the elements in question.
Hello World! Why $(document).ready() is SO cool
To demonstrate the beauty of this functionality, let’s recreate the standard introduction to Javascript: a “Hello World” alert box.
The following markup shows how we might have run a “Hello World” alert without jQuery:
CrossBad markup:
<script language="javascript">
alert('Hello World');
</script>
TickGood markup:
Using this functionality in jQuery is simple. The following code snippet demonstrates how we might call the age-old “Hello World” alert box after our document has loaded. The true beauty of this markup is that it lives in an external Javascript file. There is NO impact on the (X)HTML page.
$(document).ready(function()
{
 alert('Hello World');
});
How it works
The $(document).ready() function takes a function as its argument. (In this case, an anonymous function is created inline—a technique that is used throughout the jQuery documentation.) The function passed to $(document).ready() is called after the DOM has finished loading and executes the code inside the function, in this case, calling the alert.

DYNAMIC CSS RULE CREATION

One problem with many DOM scripting effects is that they often require us to hide elements of the document from view. This hiding is usually achieved through CSS. However, this is less than desirable. If a user’s browser does not support Javascript (or has Javascript disabled), yet does support CSS, then the elements that we hide in CSS will never be visible, since our Javascript interactions will not have run.
The solution to this comes in the form of a plugin for jQuery called cssRule, which allows us to use Javascript to easily add CSS rules to the style sheet of the document. This means we can hide elements of the page using CSS—however the CSS is ONLY executed IF Javascript is running.
CrossBad markup:
HTML:
<h2>This is a heading</h2>
<p class="hide-me-first">
This is some information about the heading.
</p>

CSS:
p.hide-me-first
{
 display: none;
}
Assuming that a paragraph with the class of “hide-me-first” is going to first be hidden by CSS and then be displayed by a Javascript after some future user interaction, if the Javascript never runs the content will never be visible.
TickGood markup:
HTML:
<h2>This is a heading</h2>
<p class="hide-me-first">
This is some information about the heading.
</p>

jQuery Javascript:
$(document).ready(function{
 jQuery.cssRule("p.hide-me-first", "display", "none");
});
Using a $(document).ready() Javascript here to hide the paragraph element means that if Javascript is disabled, the paragraphs won’t ever be hidden—so the content is still accessible. This is the key reason for runtime, Javascript-based, dynamic CSS rule creation.

4. Conclusion

jQuery is an extremely powerful library that provides all the tools necessary to create beautiful interactions and animations in web pages, while empowering the developer to do so in an accessible and degradable manner.