Learn Angular 4.0 In 10 Days - Day One

HyperText Markup Language (HTML) was invented in 1990 by Tim Berners-Lee—a famous physicist and computer scientist—while he was working at CERN, the European Organization for Nuclear Research. He was motivated to discover a better solution to share the information among researchers of the institution in a very quick and easy way. To support that, he also created the HyperText Transfer Protocol (HTTP) and its first server, giving rise to the World Wide Web (WWW).

At that time, HTML was used just to create static documents with hyperlinks, allowing the navigation between them. However, in 1993, with the creation of Common Gateway Interface (CGI), it became possible to demonstrate or develop dynamic content generated by server-side applications. One of the first languages used for this purpose was Perl, followed by other languages such as Java, PHP, Ruby, and Python. However, the technology kept moving forward, at first with technologies such as Flash and Silverlight, which provided an amazing user experience through the use of plugins. At the same time, the new versions of JavaScript, HTML, and CSS had been growing in popularity really fast, transforming the future of the Web by achieving a high level of user experience without using any proprietary plugin.

AngularJS is a part of this new generation of libraries and frameworks that came to support the development of more productive, flexible, maintainable, and testable web applications.

What is Angular?

Basically, Angular is an open source, JavaScript-based web application development framework. Definition of Angular as put by its official documentation is as follows,

“AngularJS is a structural framework for dynamic web applications. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application components clearly and succinctly. Its data binding and dependency injection eliminate much of the code you currently have to write. And, it all happens within the browser, making it an ideal partner with any server technology.”

It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Angular JS supports JavaScript MVC (MVVM) frameworks.

The most common question before starting AngularJS is what is AngularJS? In common words, it is -

A MVC Structured Framework

A Single Page Application Framework

A Client Side Templating

A Language where the written code can be easily tested by unit testing

Now, the above key features of AngularJS contain the main concept of innovations of Angular. The main idea behind Angular is the separation between HTML manipulation and JavaScript logic in the web pages so that the HTML page and JS logic can be developed simultaneously. It always give us faster productivity from a developer's point of view. Also, Angular provides us a structured JavaScript framework which can perform unit testing easily.
General Features of AngularJS

The most important and remarkable general features of AngularJS are,

Angular JS is a efficient framework that can help developer to develop Rich Internet Applications (RIA).

AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.

ngularJS is a framework to build large scale, high performance, and easy-to-maintain web applications.

Why Angular is known as a Framework

Before exploring AngularJS in depth, let us consider exactly what is AngularJS? What do we mean by a “framework,” and why would we want to use one? The dictionary definition tells us that a framework is “an essential supporting structure.” That sums up Angular very nicely, although Angular is much more than that. Angular is a large and helpful community, an ecosystem in which you can find new tools and utilities, an ingenious way of solving common problems, and, for many, a new and refreshing way of thinking about application structure and design. We could, if we wanted to make life harder for ourselves, write our own framework.

Realistically, however, for most of us, this just isn’t possible. It almost goes without saying that you need the support of some kind of framework, and that this framework almost certainly should be something other than your own undocumented (or less than well understood) ideas and thoughts on how things should be done. A good framework, such as AngularJS, is already well tested and well understood by others. Keep in mind that one day others may inherit your code, be on your team, or otherwise need to benefit from the structure and support a framework provides.

The use of frameworks isn’t uncommon; many programmers from all environment of coding rely on them. Business application developers use frameworks, such as the Microsoft Entity Framework, to ease their pain and speed up development when building database-related applications. For example, Java programmers use the LibGDX framework to help them create games. I hope I have explained the need for a framework and, more specifically, the fact that AngularJS is a great choice.

Architecture Concept

It's been a long time since the famous Model-View-Controller (MVC) pattern provided by Microsoft Corporation started to gain popularity in the software development industry and became one of the legends of the enterprise architecture design. Basically, the model represents the knowledge that the view is responsible for presenting, while the controller mediates the relationship between model and view. After a lot of discussions about which architectural pattern needed to follow by the Angular JS framework, its authors declared that from now on, AngularJS would adopt Model-View-Whatever (MVW). Regardless of the name, the most important benefit is that the framework provides a clear separation of the concerns between the application layers, providing modularity, flexibility, and testability.

In terms of concepts, a typical AngularJS application consists primarily of a view, model, and controller, but there are other important components, such as services, directives, and filters. The view, also called template, is entirely written in HTML, which provides a great opportunity to see web designers and JavaScript developers working side by side. It also takes advantage of the directives mechanism, which is a type of extension of the HTML vocabulary that brings the ability to perform programming language tasks such as iterating over an array or even evaluating an expression conditionally.

Behind the view, there is the component. At first, the component contains all the business logic implementation used by the view. However, as the application grows, it becomes really important to perform some refactoring activities, such as moving the code from the controller component to other components (for example, services) in order to keep the cohesion high.

The connection between the view and the controller is done by a shared object called model. It is located between them and is used to exchange information related to the model. The model is a simple Plain-Old-JavaScript-Object (POJO). It looks very clear and easy to understand, bringing simplicity to the development by not requiring any special syntax to be created.

Advantages of Angular JS

AngularJS, commonly referred to as Angular, is an open-source web application framework maintained by Google and a community of individual developers and corporations to address many of the challenges encountered in developing single-page applications. The library works by first reading the HTML page, which has embedded into it additional custom tag attributes. Those attributes are interpreted as directives telling Angular to bind input or output parts of the page to a model that is represented by standard JavaScript variables. The values of those JavaScript variables can be manually set within the code, or retrieved from static or dynamic JSON resources.

The main advantages of the Angular JS are,

No need to use observable functions; Angular analyzes the page DOM and builds the bindings based on the Angular-specific element attributes. That requires less writing, the code is cleaner, easier to understand and less error prone.

Data binding occurs not on each control or value change (no change listeners) but at particular points of the JavaScript code execution. That dramatically improves performance as a single bulk Model/View update replaces hundreds of cascading data change events.

Quite a number of different ways to do the same things, thus accommodating to particular development styles and tasks.

Extended features such as dependency injection, routing, animations, view orchestration, and more.

Supported by IntelliJ IDEA and Visual Studio .NET IDEs.

Supported by Google and a great development community.

AngularJS is more intuitive as it makes use of HTML as a declarative language. Moreover, it is less brittle for reorganizing.

AngularJS is a comprehensive solution for rapid front-end development. It does not need any other plugins or frameworks. Moreover, there are a range of other features that include Restful actions, data building, dependency injection, enterprise-level testing, etc.

AngularJS is unit testing ready, and that is one of its most compelling advantages.

What’s New in Angular 4 In Compare Angular JS?

Angular 2.0 was of officially announced at the ng-conference in October, 2014. This version won’t be a complex major update, rather a rewrite of the entire framework and will include breaking changes. The final version of Angular 2 was introduced by Google June 2016 and Later in March 2017, Google introduced another new version of Angular JS which is called Angular 4. Angular 4 or angular is a TypeScript-based open-source front-end web application platform led by the Angular Team at Google. Angular is a complete rewrite from the same team that built AngularJS. But let me tell you that Angular is completely different from AngularJS. Let us understand the differences between Angular and AngularJS:

The architectural framework of an Angular application is different from AngularJS. The main building blocks for Angular are modules, components, templates, metadata, data binding, directives, services and dependency injection.

Angular was a complete rewrite of AngularJS.

Angular does not have a concept of “scope” or controllers instead, it uses a hierarchy of components as its main architectural concept.

Angular has a simpler expression syntax, focusing on “[ ]” for property binding, and “( )” for event binding

Mobile development – Desktop development is much easier when mobile performance issues are handled first. Thus, Angular first handles mobile development. The new Angular version will be focused on the development of mobile apps. The rationale is that it’s easier to handle the desktop aspect of things, once the

Modularity – Angular follows modularity. Similar functionalities are kept together in same modules. This gives Angular a lighter & faster core. Various modules from previous version of Angular Js has been removed from Angular’s Core for better performance.

Angular 2 will target ES6.0 and almost all modern browsers. Building for those browsers means that various hacks and workarounds that make angular harder to develop can be eliminated along developer to focus on code related to their business domain.

Now, let us talk about Angular 4. Angular community has introduced some significant changes to Angular 4 and therefore, the major version number has been changed from 2 to 4 (skipping 3). The reason behind directly jumping to Angular 4 and skipping the version 3 was that the router package was in version 3.x, so instead of putting everything to 3.0 and the router to 4.0, the team chose to upgrade the versions of all the ng - modules to 4.0.

The following points introduced in Angular 4.0,

TypeScript 2.1+ RequiredTypeScript 2.1 and 2.2 have brought really nice features you should check out. Angular 4 now supports them (and you will soon be able to activate the new strictNullChecks TypeScript option for example).

ModuleID RemovedThey have added a new SystemJS plugin which dynamically converts "component-relative" paths in templateUrl and styleUrls to "absolute paths" for you.

Ahead of Time CompilationView Engine: As we know, in AoT mode, Angular compiles your templates during the build, and generates JS code whereas in case of Just in Time mode, this compilation is done at runtime. Now, AoT has several advantages, like we will get to know that our templates is incorrect at build time instead of having to wait at runtime, and the application starts faster (as the code generation is already done). The downside of AoT that people were facing was that the generated JS is generally bigger than the uncompiled HTML templates. So, in the vast majority of applications, the package is in fact bigger with AoT. The team worked quite hard to implement a new View Engine, that produces less code when you use the Ahead of Time compilation. The results are quite impressive on large apps, while still conserving the same performances.

AnimationsAngular Team have segregated animation package from @angular/core as a separate and dedication package. Therefore, if you don’t use animations, this extra code will not end up in your production bundles.

Template is now ng-templateThe template tag is now deprecated, which mean you should use the ng-template tag instead. It still works though. Now Angular has its own template tag called ng-template. You will have a warning if you use the deprecated template somewhere when you update to Angular 4, so it will be easy to spot them.

What is TypeScript?

As per the previous discussion, it is clear that Angular 2 or 4 version is totally developed on the basis of Typescript where as previous version of AngularJs is depends on Javascript or JQuery library. Actually TypeScript is a super set scripting language of Javascript. So before going to discuss about typescript, first we need to kwno what is TypeScript? As per the google, the definition of typescript is

“TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language. Anders Hejlsberg, lead architect of C# and creator of Delphi and Turbo Pascal, has worked on the development of TypeScript.”

It encourages software developers to more declarative style of programming like interfaces and static typing, offers modules and classes, and most importantly, integrates relatively well with popular JavaScript libraries and code. It totally follows the OOPS concept. Or we can say TypeScript is a transpiler. Many software developers will get very confused about Transpiler. It may be compiler but actually it is a transpiler. If you do not know about transpiler, then learn ahead. Actually transpiler means it basically converts one language into another language.

How to Install Typescript?

So, before going to start Angular 4.0, we first need to know how to install typescript tool. For installing typescript, we first need to install NodeJs. The Latest version of NodeJS can be downloaded from the below urls,

https://nodejs.org/en/

For installing TypeScript we can download the latest version of typescript either by using command line argument using node js or if we use Visual Studio then we can directly download it from Nuget Package Manager.

Command Line for Install Typescript ,

npm install -g typescript

Or from Visual Studio

In the previous section, we will discuss about how to set the environment of an angular 4 projects using visual studio. Also we will develop our first program in Angular 4. Before going to start the program, lets’ discuss about the project configuration.

The existence of a tsconfig.json file in a project directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled in one of the following ways

By invoking tsc with no input files, in which case the compiler searches for the tsconfig.json file starting in the current directory and continuing up the parent directory chain.

By invoking tsc with no input files and a --project (or just -p) command line option that specifies the path of a directory containing a tsconfig.json file, or a path to a valid .json file containing the configurations.

When input files are specified on the command line, tsconfig.json files are ignored.

Sample of tsconfig.json

{

"compileOnSave": true,

"compilerOptions": {

"target": "es5",

"module": "commonjs",

"moduleResolution": "node",

"sourceMap": true,

"emitDecoratorMetadata": true,

"experimentalDecorators": true,

"removeComments": false,

"noImplicitAny": false,

"declaration": false,

"typeRoots": [

"node_modules/@types"

],

"lib": [

"es2017",

"dom"

]

}

The "compilerOptions" property can be omitted, in which case the compiler’s defaults are used. For full list of supported Compiler Options, please visit the below links -

https://www.typescriptlang.org/docs/handbook/tsconfig-json.html

By default all visible “@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible; specifically, that means packages within ./node_modules/@types/,../node_modules/@types/, ../../node_modules/@types/, and so on.

package.json

This document is all you need to know about what's required in your package.json file. It must be actual JSON, not just a JavaScript object literal. A lot of the behavior described in this document is affected by the config settings described in npm-config.

name
The most important things in your package.json are the name and version fields. Those are actually required, and your package won't install without them. The name and version together form an identifier that is assumed to be completely unique. Changes to the package should come along with changes to the version. Some rules related to name attribute

The name must be less than or equal to 214 characters. This includes the scope for scoped packages.

The name can't start with a dot or an underscore.

New packages must not have uppercase letters in the name.

The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can't contain any non-URL-safe characters.

version
The most important things in your package.json are the name and version fields. Those are actually required, and your package won't install without them. The name and version together form an identifier that is assumed to be completely unique. Changes to the package should come along with changes to the version.

description
Put a description in it. It's a string. This helps people discover your package, as it's listed in npm search

keywords
Put keywords in it. It's an array of strings. This helps people discover your package as it's listed in npm search

homepage
The url to the project homepage

license
You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.

People fields : authors, contributors
The "author" is one person. "contributors" is an array of people. A "person" is an object with a "name" field and optionally "url" and "email".

files
The optional "files" field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. If the files array is omitted, everything except automatically-excluded files will be included in your publish. If you name a folder in the array, then it will also include the files inside that folder (unless they would be ignored by another rule in this section.).

directories
The CommonJS Packages spec details a few ways that you can indicate the structure of your package using a directories object. If you look at npm's package.json, you'll see that it has directories for doc, lib, and man.

system.config.js

system.config.js is the one which allows to load modules(node modules) compiled using the TypeScript compiler.map refers to the name of modules to JS file that contains the JavaScript code. It allows to configure SystemJS to load modules compiled using the TypeScript compiler. For anonymous modules (one module per JS file), it allows to map the name of modules to JS files that actually contains the module JavaScript code

Now, we are going to develop our first program in AngularJs2. Now open the Visual Studio 2015 and do the following steps.

Click on File -> New -> Projects and in the New Project window, Search TypeScript Project as mentioned in the below image.