In this section, we’ll talk about Angular’s upcoming version Angular2. We will discuss major changes around Angular 2 and what to expect from this version.
Angular is currently the most popular off-course. The Angular team devised a way to allow projects to run both Angular 1.X and 2.0 code at the same time. Upgrading could now be a gradual process. In my view, this saved the framework from almost certain stagnation and the horror of thousands of challenging to maintain, legacy code bases.
CHAPTER 7: GETTING STARTED WITH ANGULAR2 & TYPESCRIPT
Creating New Project, 258
Creating Components, 259
Embedding Components, 260
Using Babel, 261
Using TypeScript, 263
Using TypeScriptWith Angular, 265
Configuring TypeScript in WebStorm, 268
Configuring File-Watcher, 269
Creating Angular App, 274
Visual Studio Code Glimpse, 279
About the author, 290
Angular JS fills this gap very nicely by providing a wrapper around JQuery on the top of DOM especially in the areas of writing boilerplate code and making application more maintainable, reusable and testable. Angular JS been written by keeping testing in mind. Hence, it ensures that each and every piece of Angular JS is testable. Angular JS fits in all the scenarios where in basic stuffs like Data-Driven programming, Declarative programming, and Modular programming is required. Angular JS is evolving very rapidly. Their development team and community are adding tons of useful features to this library to make the same more robust and useful.
Who This Book Is For
FROM THE MANAGER’S DESK
Today, no web developer worth his salt can afford to ignore learning concepts and tools required to develop SPA applications. There is a need today more than ever before to develop applications faster, modular, so large distributed teams with diverse skill sets can work in parallel to create an application that can provide the best of user experience and yet be performant, maintainable, extendable and testable. AngularJS is the framework to go to achieve all the above goals.
This book is an excellent resource for anyone beginning to learn Angular. Rahul has been extremely diligent in coming up with examples that are real world like and yet do not take away the reader’s attention from angular concepts he is trying to explain. The concepts are first clearly explained followed by code for building a moderately complex application. Each area of Angular is thoroughly dealt with including the tools in Angular eco system such as WebStorm, Visual Studio Code, Karma, and Yeoman. Overall, it is an enjoyable and informative read.
AngularJS has come a long way since its inception in 2009. Its initial success was spectacular when it helped to reduce 17,000 lines of code to 1,500 lines of code at Google in the Google Feedback project. Hevery, a developer in the Google Feedback project, could rewrite the code that was written over 6 months in flat 3 weeks using the AngularJS framework. Moreover, the product that was built in 3 weeks was also of a better quality in terms of ease of testing. This initial success of this platform made many Googlers support continuous development of this open source framework.
This book has done an excellent job in introducing this able platform to software developers. Rahul Sahay, the author has built an example web application, which has helped to reinforce the concepts of the project through practical implementation. The book will serve as a good tutorial and a good reference for all the developers who want to leverage the enormous capability of the AngularJS framework. With Single Page Applications and other associated frameworks such as Node.js getting popular and popular, this book is being released at an apt time. Enjoy the technical feast!
How this book is structured
Chapter 1, Getting Started
Starts by explaining what is Angular, why it is needed? How it fits in web application. You will also learn the overview of Angular JS. Then, you will understand how to build Single Page App.
Chapter 2, Controllers & Markups
In this chapter, you will learn scope and controller, which is the nerve of any ng app. Then, writing your first controller. Here, you will be using different ng pieces to display the info on the page via controller.You will also see directives, filters, and expressions in action. Then, in the end, you will be able to do client side validation for the page.
Chapter 3, Services
Services are very important ingredient in angular application. You will begin this section, by learning what are services, how do you create them and then how to register the same with angular app. After that, you will be using some built-in angular services and writing custom services for specific scenarios. Here, I have also introduced Angular JS Graph to visualize the app in console.
Chapter 4, Routing
Routing is the place, where you actually convert your angular app into Single Page App. You will learn how to configure the routes. Then, you will also learn how to configure Parameterized routes. Last but not the least you will be using location service with routes.
Chapter 5, Creating Custom Directives
In this section, you will learn how to get started with custom directives design. Why do you need them in any angular app? How it enhances the reusability and maintainability of the code? You will also learn how to encapsulate elements. Then, you will learn how to isolate the scope from the parent scope and many things that are more relevant which is required on day-to-day basis for any angular app.
Chapter 6, Testing Angular
This is the last chapter of this book where in you will learn how to get started with Angular Testing. First, you will learn how to setup the dev environment to launch the Karma Test runner. Then, you begin this section by writing simple controller tests. Afterwards, you will be learning how to write different kinds of tests and in the end, there will be a bonus section, where in you will learn how to inspect and troubleshoot your angular app.
Chapter 7, Getting Started With Angular 2 & TypeScript
This is the last chapter of the book where you will get the feel of upcoming Angular 2.0 version. Here, you will get started with new angular features. Then, we will see how to get started with angular 2.0 with simple demos using Typescript, ES6 and ES5 as well. After understanding TypeScript basics, we will build one small Movie-Review version with TypeScript & Angular.
Again, this book would not have been possible without the loving support of my wife Nivi, who had to take over much of the household responsibility apart from her teaching activities. Appreciation also goes out to my Mom and Dad for believing in me and always keeps on encouraging me to complete the book in a best possible way. Moreover, I would also like to thank Sita and Piram for sharing their views on the book. In addition, I would also like to thank Arun and Mayank for doing the technical review and suggested few changes around it.
In the end, you know how it is, you pick a book and flip to Acknowledgement’s page and find that author has once again dedicated the book someone close to him, not to you. Not this time. I would like to thank all the readers whole-heartedly for choosing the book. Finally, I would like to thank readers of my blog (http://myview.rahulnivi.net). Many of you have contributed by asking questions, providing feedback, and inspiring and encouraging me in everything, I do.
Chapter 1: Getting Started
WHAT DO you find in this CHAPTER?
Angular JS Advantages
Comparison with JQuery
Angular Movie App Overview
Angular Skeleton Project
The Core concept behind Angular JS is MVC Architectural Pattern. MVC stands for Model-View-Controller. MVVM (Model-View-ViewModel) also similar to MVC, just a design pattern to separate the units of responsibility in different containers. This kind of design pattern gives developers a sense of architectural thinking that how they want to separate the different layers of their web application. MVC design pattern splits the app into three distinct pieces. They are-
Model: – Model is nothing but data repository for the application usually fetched from the server and served on the web page via controller. Hence, any web application that is not static, which is getting data is coming via model only.
View: – View is nothing but the presentation layer of web application. You can also think view as generated HTML. Views are basically dynamic in nature as it entirely depends on the data being fetched from the server and how it is finally presented.
Controller: – Controller is the central processing unit of any app that is based on MVC design pattern. Once user requests the page, that is getting intercepted by controller and then controller decides where to pick the data from and finally pick which template.
As a result, each unit is responsible for one and only thing. Model means data, View means UI and controller is the business logic. Moreover, each unit is independent of each other, which makes angular more robust, unique and easy to maintain.
In this section, we will learn more about Angular JS architecture. However, before discussing angular architecture, let us discuss conventional web application architecture in brief. As you can see in the below diagram, whenever you make a request it is going to server and fetching the entire asset time and again which is very resource intensive, hence puts pressure on the bandwidth, on the server and end result is site response time is slow.
However, in case of angular, it loads all the assets and required components in the first load only. Then, whenever next request comes for any different link on the page, it only replaces JSON there. This way, angular makes any app very lightweight and fit for any device.
One more point to note here that modern day apps needs that universal architecture support which means you write once and use everywhere like shown below.
Angular js advantages:-
In this section, we are going to discuss the Angular JS benefits. However, from the previous section, you might have got the glimpse of benefits of angular.
Since, there are many things already built in Angular JS framework, hence it needs only proper API implementation to get the functionality running rather than using JQuery.
As, I said, Angular is built on the top of MVC design pattern. Hence, it helps keep your code modular, maintainable, reusable and testable.
Angular JS declarative nature gives a snapshot to developer by just looking at the code that what would have been intention behind writing this code.
Angular JS supports many third party libraries, which people need as to style the app, notify the users and many other use cases that people need on day-to-day basis.
Comparison with Jquery:-
In this section, we will do a brief comparison between JQuery and Angular JS. I have mentioned detailed side-by-side comparison between the two in below table.
Abstract The DOM
Cross Module Communication
Integration Test Runner
Unit Test Runner
However, JQLite is already built-in in angular. Hence, you do not need to explicitly use JQuery for any DOM manipulation. You can use JQuery stuffs by calling like angular.element().
Modules in Angular JS are one of the key reasons for keeping application modular. Below is the simple diagram of modules briefly.
As you can see in the above screen shot, modules let you create all underlying pieces. All these pieces we will understand piece by piece in coming chapter. One more point to understand an angular application can have as many modules as required and all of these are dependent on each other like shown below.
Hence, if your app module is dependent on some other module, then that dependent module can be injected before executing the actual app module. We will see all these things in detail in coming chapters.
Visual Studio Code
Sublime and many more
Angular movie app review:-
I always like talking about the application, which you will be building here, with app snapshots, first. Below is the home page of the application.
Now, when you click on any of these movies, it will take you to the corresponding pages as shown below-
Similarly, you can post new movie like shown below.
You will also learn how to write client side validation like shown below.
Moreover, when everything goes well, then Post Movie button will enabled as shown below.
As you can see that, once image URL pasted there, it produced the relevant image. This is called data binding, which you will learn in coming chapters. Then, when you click Edit profile, it will produce the below screen.
Here, you will learn the power dynamic data binding on the fly using Angular JS. Like, when I type my email id in email address box, it will fetch my image as shown below.
Similarly, when you click on the last link, then this will produce the below page.
Hence, let us suppose if we enter values as shown below in the screen shot, respective cache size value also getting changed.
Then, you can retrieve the same by providing key as shown below.
Similarly, you can delete the same based on key or flush entire set. We will discuss all these terminologies in coming chapter. We will go through complete list of directives we generally use on day-to-day basis. However, one directive that I used recently in one demo wanted to show here. This directive is used for embedding you tube videos in your angular application, angular way. Below is the glimpse for the same.
I have also explained normal authentication service by enabling user to do registration on the site and then login accordingly as shown below.
Apart from this, I have also explained how to get started with yeoman scaffolding template generators for angular and other required dependency. You will learn the same in coming chapters. However, below is the short glimpse for the same.
After doing improvisation on the generated code, app will look like as shown below.
I have also discussed about Angular2 Features in the last chapter. Then how start with TypeScript and write the angular app using that. Below is the glimpse of the same.
This also produced me the required output at the bottom of the screen in JSON format.
Then, how to get started with TypeScript with simple TypeScript workflow discussion.
I hope you have enjoyed the app glimpse. Hence, without wasting time let us get started.
Angular skeleton project:-
In order get started with Angular JS, you can download the skeleton project from here (https://github.com/rahulsahay19/Movie-Review-Angular-Skeleton) , if you want to code along with me on the same study. However, it is not necessary to follow this convention. You can surely apply the angular techniques in any angular project that you want.
In this chapter, we have started with Angular JS overview. We started with basic understanding of angular then we also had a glimpse of MVC structure on which Angular is laid upon. Then, we discussed angular architecture in detail by comparing the same with conventional web-app architecture. We have also done concise comparison with JQuery, in order to understand how Angular JS fits in modern day web architecture. Then, we summarized this chapter by giving brief overview of the application, which you will be building along.
In today’s discussion, we will see the glimpse of Angular 2 in a nutshell. Angular 2 is getting released coming December 2015. This release is going to bring some major path breaking changes like major performance improvements and feature enhancements. In more than 400 commits, Google has fixed more than 100 bugs and added around 30 additional features. These stats are just the initial stats and final list will have many more features. However, I thought it would be great, if I can provide a brief snapshot around the same. AngularJS 2 is for mobile apps. It is for desktop as well, but major focus is on mobile. With this, let us go ahead and look at the complete list of features.
Mobile First: – Angular Team, at ng-conf made it clear they will go for mobile first approach. I think this is bold and brilliant step around that. These days, demand is very adaptive. Hence, if you can fit perfectly in mobile environment then I think desktop apps will be cakewalk.
Loosely Coupled Modules: – Angular Team has been detaching from its several core versions now. At the same time, community started offering very interesting modules like ui-router. Both, angular team and community have successfully built an ecosystem, which keeps on increasing. You can find more details around the same @ http://ngmodules.org/.
Modern Browsers: – The set includes Chrome, Firefox, IE10/11, Opera, Safari and all latest mobile browsers support.
ECMA Script 6:- All code in AngularJS is written entirely in ES6. Since, ES6 don’t run in browsers today, hence google is testing the same using traceur-compiler to generate ES5 script which runs everywhere. Do not worry if you do not want to upgrade to ES6, you can still write entire angular 2 in ES5.
Dependency Injection: – Dependency Injection is still a key differentiator between AngularJS and other client side frameworks in eliminating much of application’s wiring code and making testability-by-default. Based on ES6, it provides less complex syntax, declarative annotations and lazy loading.
Templating & Directives: – The ability to specify template directly in HTML and extend its syntax are like cakewalk in AngularJS. In Angular 2, this process has become more simplified. It also boosts performance.
Touch Animations: – Angular team is working on touch animations to make the performance on mobile devices much better than ever before. The main goal here is creating a module that implements usage patterns using native browsers features.
Router: – The initial angular router was designed just to handle simpler use cases. As AngularJS grew, Angular team added tons of new features to it to extend it further.
Persistence: – There was always a room between fetching the data from the server and fetching the data from local storage like from browser. Mobile apps need to work on the same lines. Angular team is working on the same to provide higher level of abstraction. Apart from these there are many other features which are getting added by angular team.
In this section, we’ll delve further and enhance the app where we stopped last time. Now, let us go ahead and improvise the UI a bit, so that it feels good and look good. In order to get started, I will make use of some bootstrap templates which you can refer here @ Bootstrap. Now, from here i will pick Cyborg theme as shown below in the screen shot.
From here, I will just go ahead and download the css file and save in my bower components as shown below in the screen shot. I could have placed it in my app styles folder as well, but there my fonts and other dependent items are not there, hence it’s good to have consistency and place it at one place. Here, i have downloaded two themes cyborg and superhero.
Then, i have commented the initial reference of bootstrap and referenced new one as shown below.
With the above change in place, it produced the below theme.
Now, it feels better. I have also improvised a bit in the movies template with the below snippet.
One more change i have done for menu highlighting with the minor change as shown below.
With the above change in place, it will look like as shown below.
Now, let us go ahead and create Movies controller to put some data in. For doing that, I have used my yo generator to do the same.
Therefore, this is the benefit of using yo generator. Out of the box, it gave me test file as well. Now, let us go ahead let us put some data in there to display on the page. Off-course currently, it will be static data. Later we will see how to couple the same with data fetched from the server. By the way, below snippet is the default one created by generator.
Looks ok to me. But, I don’t need these stuffs, hence I will modify the same and make some necessary changes as shown below.
Now, i need to do corresponding view changes
With the above change in place, it will produce the below result. Although the page doesn’t look super impressive, but that’s ok. UI is least bothered for now.
I have also added two more views for Login page and Register as shown below in the screen shot.
Functionality of this, we will see in coming section. Till then stay tuned and Happy coding.
In today’s section, we will begin customizing the project our way. 1st let us open the project in WebStorm and let’s inspect the folder structure. Below is the folder structure of yeomen project looks like.
Now, if you expand node modules, then you will see, node has installed many dependencies which include testing dependencies as well.
However, if you are not familiar with testing frameworks like jasmine. I would suggest, visit http://jasmine.github.io/ website, how to get started with this. Now, if you delve further in the folder structure, you will find that it gave us some per-written test to get started.
Now, if you open the test, then it will look like
In order to run this test, here in webstorm, i need to make few configuration changes like shown below.
Then, do the Karma environment settings as shown below.
Then, click on apply and then ok. With this, Config section for karma will get enabled in webstorm.
By, clicking on this play button, it will launch the karma server and execute the test as shown below.
This shows that all my per-written tests are executing fine, which means all the components are setup correctly and everything is looking healthy, hence we can proceed with app development. Hence, now let us turn our attention towards, app folder and open index.html page. Below is the snippet of default HTML page.
Here, you can see many things like boiler plate code for HTML 5 template, plus menus, then we have google analytics also built in here. Apart from this from angular perspective, you can find that main controller is injected here with ng-view in place. One point to note here, here i have modified app name and one of the menu section and once i saved the same, it just automatically refreshes in the browser, i don’t have to refresh the same manually.
And the reason for this is watch window which is taking live update and update at the same time in UI as shown below in the screen shot. This uses Grunt script which detects the change and updates the UI at the same time.
Now, the next thing which i will do is register a movies view with angular generator from the webstorm terminal window. If you are not using webstorm, doesn’t matter, you can open another command prompt and do from there.
Upon, successful creation, it will display the below message.
And, if you refer the views folder, then you will see that new view has been generated.
And, when you open this file, it will look something like below
It’s entirely up-to you, whether you want to use generator to create the template for you or you want to do the same manually.Next thing, i need to define the route for the same. Below is the modified snippet for the same.
Since, i do not have any logic for this template and just a simple plain HTML, hence i have not provided controller name and aliasing name.
With the above change in place, I have also changed menu section in index page as shown below.
Now, when i go ahead click Movies link, it will produce the below shown result, prettiest page in the world; jokes apart.
We will improvise more on the functionality and UI in coming section. Till then stay tuned and happy coding.
1,425 total views, no views today
Subscribe For Latest Updates!
Signup for My View newsletter and get notified when I publish new articles for free!