Getting Started with TypeScript: Angular 2 (1/N)

Hello All,

Thanks a lot to all of you for liking my first AngularJS 1.X series and I am very glad to receive thousands of responses and feedback. I was planning to write the similar series on Angular 2 but got bit busy with various things. Also I was working on a course on ASP.NET Web API using ASP.NET Core which you can find at Learning ASP.NET Web API. In the mean time so many blog readers requested me for the same. Today I am going to write first post on Angular 2, specifically Typescript.

Download the pdf version of my AngularJS 1.X series from here.

As Angular 2 was first announced by Google around two years back in 2014 since then various changes has taken place in the framework and continuing. The final release is yet to be out. Due to the kind of breaking changes with previous version it is introducing, initially there were lots of apprehensions in the community around it. But the Angular team has successfully addressed most of the concerns as the times passed. Now it is approaching to final release and we already have couple of RC releases so we are not too late with it. But it is high time to start.

Why Angular 2?

It is one of the most asked questions about Angular 2. As we have already a robust framework (AngularJS 1.X) which is serving the purpose quite beautifully for small to large enterprises, do we need this kind of changes at all?

The answer is Yes. There are quite a few reasons. Let’s see that

  1. There are major performance improvements in all the areas whether it is bootstrapping, Data binding, event handling etc. Leveraging Web workers and using other libraries also got simplified.
  2. As this is the age of mobile, Angular 2 has been developed by keeping it mind since beginning. The same code renders differently based on browser or mobile app.
  3. One of the hardest things to understand in Angular 1 was $scope which is no more in Angular 2. Angular 2 uses zone.js for the change detection.
  4. No more controllers and we will deal with Components here
  5. Write less code with Typescript and leverage the OOPs concept.

So we have seen some of the key benefits of Angular 2 but it does not mean you just upgrade the Angular 1 to 2. As it is completely new framework with little commonalities with previous one, it is advised to use it with new applications while old one can happily use Angular 1 without any issue.

How to start with Angular 2?

In AngularJS 1.X, we have used plain JavaScript for writing the code but as we are seeing for long, writing JavaScript code for enterprise level applications is quite tough and become unmanageable as the time passes. Even for small applications as they grow, it becomes tough to manage. Angular 1.X resolves this problem a bit by structuring the code and writing loosely coupled system. But JavaScript itself is not a type-safe language and does not allow features of OOPs. To overcome these problems, Angular Team announced AtScript at ngEurope conference in Sep 2014 and shared the new (Angular 2) framework is developed using it. Microsoft was also working on similar language TypeScript so both got together and in March 2015, they announced that the features of AtScript will be available in TypeScript 1.5 and the complete Angular 2 framework got built using TypeScript.

ECMA which defines the standards for JavaScript also understood the challenges of it and came ECMA 6 (June 2015) which includes the concept of classes, modules etc. and ECMA 7 in June 2016. Lets see how does all fit together.


We can see that TypeScript is super set of all, it means we can leverage the features of all the standards and languages. But currently most of the browsers supports the ECMA 5 only, it means our code cannot run as is. For that we have few compilers like tsc, webpack which compiles the typescript code to normal JavaScript so that it can run smoothly in all browsers.

As Typescript and AngularJS looks made for each other so we will use TypeScript for writing Angular 2 code and in our initial posts we will discuss some core concepts of Typescript and then introduce Angular 2. After learning basics of TypeScript, learning Angular would be very easy.

We will start learning the Class. Yes you have read it correctly. Class is new construct that got introduced with ECMA 6 and further more features are added via TypeScript.

Choosing Editor

So what editor should we use for the same. There are various options and some of them mostly used are

  1. Visual Studio 2013/2015,
  2. Visual Studio Code/Community (free)
  3. Sublime
  4. WebStorm and many more

You can use any of it. You can go for Sublime if never used Visual Studio or you can try Visual Studio community version which is free. For more details and how to use these editors, refer here.

I will be using Visual Studio and for that you just need to install a plugin and it provides very rich editor with all intellisense support and compile time errors.

Creating Class

Classes in typescript is almost similar to C# but here it is more flexible and requires less code. So let’s our first class

class Person {
    // Three properties which is by default public.
    // Types are written after the variable using the separator :
    firstName: string;
    middleName: string;
    lastName: string;

    // Class constructor accepting three parameters. 
    constructor(firstName: string, middleName: string, lastName: string) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;

    // Member function of the class
    getFullName() {
        let fullName = this.firstName + ' ' + this.middleName + ' ' + this.lastName;
        return fullName;

We have written a class Person which has three properties firstName, middleName and lastName. In this type of variables are provided after the writing itsname with a sperator “:”. All the members are by default public so these can be accessed and updated using class instance. Then we wrote constructor using the keyword constructor which accepts three parameters and initialize the internal properties. Here you can see the similar this keyword as C# which refers to current instance of the class. Also I added another method getFullName which just concatenates all the three properties and returns full name. Here you can see that we don’t need to write any keyword like function etc so we can see that it requires a lot less code and more contextual keywords.

let person = new Person("Brij", "Bhushan", "Mishra");
console.log("Mr " + person.lastName);

Now creating instance of the class is similar to C# using new keyword with passing all the parameters in constructor. As we have just one constructor we would not able to create instance by parameter less constructor. We also see another keyword let which I am using instead of var, we will discuss the differences in some later post but let should be preferred. Calling method is simple and here we just printed values in console.

Using Inheritance

Inheritance is well supported in TypeScript so we can easily extends any class. Here we need to extens keyword instead ‘:’ used in C#. Let’s extends our person class and create Employee class

class Employee extends Person {
    // Two more properties added
    employeeId: string;
    salary: number;

    // Constructor takes five parameters now. Three from base class and two derived class
    constructor(firstName: string, middleName: string, lastName: string, 
                employeeId: string, salary: number)
        super(firstName, middleName, lastName) 
        this.employeeId = employeeId;
        this.salary = salary;

    getSalary() {
        return this.salary;

As mentioned earlier, extends keyword got used for for deriving a new class. In the constructor, we used another keyword Super to call the base class constructor and that should be called inside the constructor, not after the colon (:) as C#. There we also required to use base keyword for the same.

Implementing Interface

We can also create interface and that may be implemented in a class. Let’s create an interface IBonusCalculator as

interface IBonusCalculater {

It is similar to C# and have just one method getBonus. To implement it, we need to use implements keyword. Let’s implement it in our Employee class

class Employee extends Person implements IBonusCalculater {
    // Two more properties added
    employeeId: string;
    salary: number;

    // Constructor takes five parameters now. Three from base class and two derived class
    constructor(firstName: string, middleName: string, lastName: string, employeeId: string, salary: number)
        super(firstName, middleName, lastName) 
        this.employeeId = employeeId;
        this.salary = salary;

    getSalary() {
        return this.salary;

    // Implementing IBonusCalculater's method
    getBonus() {
        return this.salary * 0.3;

So we have seen that Class in typescript provides all the key features of OOPs and uses more relevant keywords like extends, implements, constructor etc than C# which makes it more developer friendly and readable.

Now I am going the last topic which will make you excited.  Say we have two classes and there instances

class Book {
    name: string;  
class Video {
    name: string;

Are both different type. Let’s see this

let b = new Book(); = "HTML and CSS";

let v = new Video(); = "Learning ASP.NET Web API";

function PrintName(b : Book) {


Will it compile?

Yes and run without any error. Surprised.

It will print the book and video name accordingly. Typescript checks the property names for Type comparison. I find it more useful as although they are different classes but behind the scene both are same. If we add some another property in Book only then it will throw an error because the type of parameter is Book and when video does not have the property while vice versa works but we will not be access the new property of video.


In this post, We have started with little bit history of Angular 2 and discussed that how TypeScript became the primary language for Angular 2. We saw that TypeScript is superset of JavaScript including ECMA 6, ECMA 7 standards and ultimately it is converted in normal JavaScript file which is compatible with every browser. We discussed the first key concept Class with example and later we saw the most important thing that two different class with same properties are considered similar here. In the next post, we will discuss about Decorator and Components.


Received Microsoft MVP award sixth time in a Row

Hello All,

MVP_Logo_Horizontal_Preferred_Cyan300_RGB_300ppiAgain, with all of your support and feedback, I have been awarded Microsoft Most Valuable Professional award sixth time consecutively. Its really a great achievement for me and all the kudos goes to my readers, conference audiences and supporters.

I received my first award on July 2011 in ASP.NET/IIS category for the first five years. Now it got merged with other related categories and renamed as Visual Studio and Development Technologies. ASP.NET has always been close to me and if you have been following the latest changes in the framework which is ASP.NET Core then you will find it totally awesome. It’s modular, leaner, completely customizable and blazing fast which makes it closer to me. Last month, Packt published a Video Course on ASP.NET Web API using ASP.NET Core framework. I would encourage you to have a look on it.

I have been receiving lots of queries regarding Microsoft MVP program specially last couple of months so If you have any query or want any specific detail, do ask in the comment. I will answer there, so it will be useful to everybody.

Again thanks a lot to all of you. Do keep sharing your feedback and ask any specific question regarding MVP program here.


My Video Course : Learning ASP.NET Web API

Hello All,

9781785885945I am very happy to announce that my video course  Learning ASP.NET Web API using ASP.NET Core 1.0 got published. This course is for all the ASP.NET Developers who have little or no experience to Web API as it starts from basics and covers all the key aspects of Rest-ful services with real world examples. It will be similarly helpful to experienced Web API devs because developing it using ASP.NET Core is completely different and many old concepts cannot be used as it is.

The vision of the course is that the viewers understand that how to develop a RESTful web API using the ASP.NET Web API service, and be able to implement a service with a range of data transfer and handling operations. They will understand RESTful service architectures and how different types of application data can be exposed with a web API, to different client endpoints.Let me give overview of the course.

The key features of the course are

  • Develop a complete enterprise level REST based HTTP services from scratch using ASP.NET Core Web API with latest standards.
  • An example driven course from starting from basics of REST with brief description of new ASP.NET framework ASP.NET Core.
  •  Discusses all the building blocks: Routing, Controllers, Content Negotiations and security with advance topics like versioning, dependency Injection, caching etc.
  • Includes the tips and best practices for making robust and scalable APIs.
  • Full of pictorial presentations for core concepts, practical examples and clear step by step instructions with tips and best practices.

What you will learn from this course.

  • Understand REST basics and its constraints with real life examples.
  • ASP.NET Core framework changes and its impact of ASP.NET Web API.
  • Building blocks of ASP.NET Web API : Routing Controllers, HTTP verbs with scenario bases example.
  • Implement various data transfer operation and Content negotiation.
  • Various security implementations options including OAuth, CORS.
  • A good hand holding of Advance topics like dependency Injection, API versioning, HTTP Caching etc.
  • Consuming Web API end points using a real world client.
  • Tips and best practices of writing better, highly scalable and performant Web API service.

To find more about the video course and watch the sample video Click here.

Thanks a lot to all of you for your continuous support and feedback. Thanks a lot to Packt publishing for providing me the opportunity for this course and being supportive throughout the journey. Thanks a lot to my friends specially Arun for his time, support, feedback and reviews. Also I cannot forget to thanks my wife Renu for being so supportive and taking care of my son Anvit during my late night hours and weekends. Without their support it would not have been possible.

This book is based on my personal learning via blogs, samples, white papers, projects, POCs and many other sources. It has no relations with any of my current and previous employers. As this course is built on ASP.NET Core 1.0 which is not yet completely out and you may expect some changes in the final version. If you find any mistakes or have some constructive feedback, you can share it with me on my mail id –  I will try my best to address that at earliest.

Again, thanks a lot to all of you for your support and feedback. I am sure you will find it useful and will be very happy to see your valuable feedback and comments.


9 Tips for Writing Secure Applications in ASP.NET

Security is one of the most important aspects of any application and when we talk about security, particularly in ASP.NET applications, it is not limited to development. A secure app involves multiple layers of security in the configuration, framework, web server, database server, and more. In this post, we’ll take a look at the top nine tips for writing secure applications in ASP.NET… Read complete post on Infragistics blog

[Video] Visual Studio Tips to make you Super Productive – Part 3

Hi All,

This video is in continuation of my last two video posts where we discussed some awesome visual studio tips which makes you super productive. In first video, we talked about tips related to Class and in second video, we discussed some other common tips for adding very common code snippets. Please find my previous two videos below

[Video] Visual Studio Tips to make you Super Productive

[Video] Visual Studio Tips to make you Super Productive – Part 2

In this video, we are going to discuss another 10 tips related to Visual Studio IDE which will help in day to day development, debugging, code review etc.

Use these tips in day to day activities and be few steps ahead 🙂


Advance CSS Selectors – Part 2

This post is in continuation of my previous post on CSS Selectors where I discussed about three primary selectors : Element, Class and Id. Later we discussed that how can we group multiple selectors to same CSS style. We also discussed how browser applies these CSS rules. There are many more powerful css selectors that we can write for targeted elements. Refer the below link to look on my previous post.

CSS selectors for beginners

Before moving ahead, lets just quickly discuss that how browser processes the HTML that it recieves from network layer. Browser has its own rendering engine which parse the HTML and constructs a DOM (Document Object Model) tree where each HTML tag added as a node in the Tree. It looks like

pic_htmltree (source:

Now let’s move to the next selectors and where we will see these selectors follows the DOM structure.

Descendant Selectors : These type of selectors contains more than one selector. It matches all the elements that are descendants of the provided element. You can also understand this is parent child relationship where it can go up to any hierarchy and the last child of the element is searched in all the elements under its parent element (ancestor). Lets see how do we write that


The above rule matches all the <a> (anchor) elements under nav tag regardless at what level it is. In the example, I have five child elements in my nav tag, in which four are <a> element and fifth is div element which contains another <a> element. This selector finds all the anchor tags under nav tag. There are some more anchor tags outside nav tag which are not selected. Lets see the example.

if we change the selector as


Then it applies the element which follows the above hierarchy and all the anchor elements inside the div which is inside nav. In the previous example, now it will applies to only one anchor (About me).

Child Selector

This selector similar to previous one but bit more constrained. It only finds the direct descendants of the provided element, i e looks only siblings elements. It is defined as

child selectorHere it only finds the <a> elements which is directly under the nav tag. I am using previous example and changing only the selector. Now this applies to only four out of five anchor tags because these four are sibling and another one is inside another div tag. Lets see the example.

Similar to earlier, we can add more hierarchy to narrow down for focused search.

Adjacent Siblings Selector

It is another selector but less used. As the name suggests, it applies to siblings or element at same level. It is combined by a symbol plus (+). One more thing, the siblings should be adjacent sibling as the name suggests and in the same order.

adjacent selector

The above selector matches all the div elements which are just after the h1 elements in the same order. In my example, I have a div element and after h1 tag. Lets see the example

We can see that in all the three selectors how DOM tree structure helps in finding the elements easily.

Let’s move another set of selectors. As we know that in the era of rich web pages, single page applications etc most of the times pages gets very heavy and contains lots of html elements. So it is our duty to write the right selector which is narrow down the search scope.

Narrowing the selectors

Dot (.) can be used for narrowing down the selectors. Let’s see an example


Here it is going to find all the div elements which has class as blueText. Here both the rule applies to same element. In the example, I have a div with blueText class where this rule applies while there is other div which is unaffected

Attribute Selectors

It is another type of selector which finds the elements that has a specific attribute and apply the provided style on that. Lets see how to use that?


Here it finds all the <a> which has a href set as  ../Index.html. In the example, I have two <a> elements with the same href value. Lets see this

We can add more power to attribute selectors by using operators. Few are


First rule finds the elements which contains Index in href. Second one selects the elements which href starts with Index and third one finds the element which href ends with the given value. This rule can be used with any attribute of an element like alt, class etc. You can explore more operators.

In this post, I have discussed lots of different selectors which can be used. Even on top it, we can have n number of combinations of these all based on our requirement. Hope you will be writing better CSS rules using these selectors.


CSS selectors for beginners

Being a .NET developer I worked most of time on server side code and could not pay required attention on the UI as there was always somebody there for that. But in recent times, we have seen awesome things happening in this front with the new technologies like HTML 5, CSS3, bootstrap etc forced me to start learning that. I have started from learning CSS and sharing today CSS selectors with examples. So let’s start from basics.

What is CSS?

CSS i. e. Cascading Style Sheet is a styling language for HTML documents. It tells an HTML document (which contains set of HTML elements) that how does the elements of HTML will be displayed mostly on browsers but also used for Paper and other media.

How to apply CSS on an element.

The simplest way to apply CSS to an HTML element is via style attribute of the element but that is not recommended approach. Recommended approach is via style sheet where we put the list of css rules. But on which html element or set of elements these css will be applied, is determined via CSS selectors. Browser has a its own selector API which traverses the DOM (document object model) and pick the elements which matches to the selectors. In this post, I have created examples at Plunker for examples so that we can see it running.

Why CSS selectors are important?

CSS selectors are very important not just because of finding an element where css applies but also these are used JavaScript libraries like AngularJS, jQuery to pick the elements from DOM to attach the behavior or data to these elements. These libraries are heavily used now a days. So using the correct selector helps in performance and writing in better code.

There are three type of selectors.

  1. Element
  2. Class
  3. Id

Element Selector

Element selector applies to all the instances of that element in the HTML document. Element selector looks like


Here p ( i eParagraph) is element name and where I defined the color as blue. So in the document, wherever a paragraph element occur it will make the font color blue, other elements would be unaffacted. In the example, there are two p element in the page and both are blue now. See it plunker

Class Selector

Every HTML element provides an attribute where we can provide the css class name. To define CSS class name, it should start with . (dot) and there is no space between dot and class name. Lets see an example

class selector

Here blueText is the css class name and the style I left as is. Now unlike the element selector where css gets applied to the corresponding elements as soon as we include it in the document, here we need to make some changes in HTML elements. We need to add the provide it the class name attribute. Here we have the advantage that we can apply to different type of elements as


In the example, I have created the css class as able and added the attribute to one paragraph(p) and one div element.

Id Selector

Id selector can be applied to only one element in the html document as HTML specification suggests to have unique id for each element. There is an attribute with name Id is available to each element where we can define it. To define the css, it should start with hash (#) sign as

Id Selector

Here also there should no space between # and name of the Id. Any element with the Id name as firstPara found by browser, this css will be applied. Here also we do not need to make any specific changes to apply the css as while defining the css style, we can simply provide css for the specific Id. As this style can be applied max one element in the document so it is less used.

In this example, I have a paragraph with Id as firstPara and for this provided CSS as above.

So we have discussed primary selectors. CSS allows many more options for writing efficient rules like Group selecters. Let’s discuss

Group Selectors

Grouping selectors means more than one selectors for the same style like


Above rule tells that this rule will be applied to those elements which either have class as blueText or with Id as firstPara,. Here we put , (comma) as separator for selectors. There is no limit on the number same or different selector. In the example. I have used firstPara to first p element and blueText to next div element. Lets see that


In this post, we have discussed the primary CSS selectors : element, class and id and saw the running examples. We have also seen the that how can we group them in to one and use different selector in code. There are more powerful feature to these selectors, we will cover in next post.