4 Common Mistakes with the Repository Pattern

As part of my new ASP.NET Core course, I’ve been encouraging my students to post their code to GitHub. While reviewing various solutions, I’ve encountered a few common mistakes in the implementation of the repository pattern.

One repository per domain

You should think of a repository as a collection of domain objects in memory. If you’re building an application called Vega, you shouldn’t have a repository like the following:

public class VegaRepository 

Instead, you should have a separate repository per domain class, like OrderRepository, ShippingRepository and ProductRepository.

Repositories that return view models/DTOs

Once again, a repository is like a collection of domain objects. So it should not return view models/DTOs or anything that is not a domain object. I’ve seen many students using AutoMapper inside their repository methods:

public IEnumerable<OrderViewModel> GetOrders() 
     var orders = context.Orders.ToList();

     return mapper.Map<List<Order>, List<OrderViewModel>(orders);

Mapping is not the responsibility of the repository. It’s the responsibility of your controllers. Your repositories should return domain objects and the client of the repository can decide if it needs to do the mapping. By mapping the domain objects to view models (or something else) inside a repository, you prevent the client of your repositories from getting access to the underlying domain object. What if you return OrderViewModel but somewhere else you need OrderDetailsViewModel or OrderSnapshotViewModel? So, the client of the repository should decide what it wants to map the Order object to.

Save/Update method in repositories

Yet another very common mistake! As I’ve explained in my YouTube video before, your repositories should not have a Save() or Update() method. I repeat: think of a repository as a collection of domain objects in memory. Do collections have a Save() or Update() method? No! Here’s an example:

var list = new List<int>();

list.Save();    // doesn't exist!
list.Update();  // doesn't exist!

Another reason your repositories should not have a Save() method is because sometimes as part of a transaction you may work with multiple repositories. And then you want to persist the changes across multiple repositories in one transaction. Here’s an example:



Can you see the problem in this code? For each change, we need a separate call to the Save() method on the corresponding repository. What if one of these calls to the Save() method fails? You’ll end up with a database in an inconsistent state. Yes, we can wrap that whole thing inside a transaction to make it even more ugly!

A pattern that goes hand in hand with the repository pattern is the unit of work. With the unit of work, we can re-write that ugly code like this:


Now, either both objects are saved together or none are saved. The database will always be in a consistent state. No need to wrap this block inside a transaction. No need for two separate calls to the Save() method!

If you want to learn how to implement the repository and unit of work pattern together, watch my YouTube video here.

Repositories that return IQueryable

One of the reasons we use the repository pattern is to encapsulate fat queries. These queries make it hard to read, understand and test actions in ASP.NET MVC controllers. Also, as your application grows, the chances of you repeating a fat query in multiple places increases. With the repository pattern, we encapsulate these queries inside repository classes. The result is slimmer, cleaner, more maintainable and easier-to-test actions. Consider this example:

var orders = context.Orders
    .Include(o => o.Details)
        .ThenInclude(d => d.Product)
    .Where(o => o.CustomerId == 1234);

Here we are directly using a DbContext without the repository pattern. When your repository methods return IQueryable, someone else is going to get that IQueryable and compose a query on top of it. Here’s the result:

var orders = repository.GetOrders()
    .Include(o => o.Details)
        .ThenInclude(d => d.Product)
    .Where(o => o.CustomerId == 1234);

Can you see the difference between these two code snippets? The only difference is in the first line. In the first example, we use context.Orders, in the second we use repository.GetOrders(). So, what problem is this repository solving? Nothing!

Your repositories should return domain objects. So, the GetOrders() method should return an IEnumerable. With this, the second example can be re-written as:

var orders = repository.GetOrders(1234);

See the difference?

What are the other issues you’ve seen in the implementation of the repository pattern? Share your thoughts!

If you enjoyed this article, please share it.

Tags: ,

Should you split your ASP.NET MVC project into multiple projects?

“Should I split my ASP.NET MVC project into multiple projects?” That’s a question that I get a lot! Almost every week! The short answer is: NO!

I’m not entirely sure how this trend started but I’ve seen some developers split an ASP.NET MVC project into multiple projects: a web project containing the presentation logic, plus two additional class libraries, often named [MyProject].BLL and [MyProject].DLL.


Also, it’s often incorrectly assumed that this structure makes an application multi-tier or 3-tier. What is a multi-tier application? It’s an application whose parts are physically distributed to different computers in a network. Web applications are often inherently multi-tired. In a web application we often have the following tiers:

  1. Client/Presentation Tier: That’s the piece running inside the user’s browser.
  2. Middle/Application/Logic Tier: That’s the part built with ASP.NET MVC (or other similar server-side frameworks) running in a web server.
  3. Data Tier: That’s the database, file system or any other kind of storage.

When we’re talking about ASP.NET MVC, we’re only talking about the application or middle tier. Separating an ASP.NET MVC project into three projects does not result in addition of new tiers in your architecture. You don’t deploy the DAL class library to a different computer! Most of the time (if not always) all these 3 projects (Web, BLL and DAL) are compiled and deployed in the same process on one machine; that is your web server. So, when someone visits your web site, these three DLLs are loaded inside a process (or more accurately an AppDomain) managed by IIS.

Layers vs Tiers

Layers and tiers are used interchangeably by some but they are fundamentally different. Layers are about logical separation, tiers are about physical separation: distributing pieces of a software application to different computers.

Layer is something conceptual in a developer’s head. A class library is not a layer, neither is a folder. You can put classes in a folder or a class library that belong to different layers and be dependent upon each other. This is a sign of bad architecture and coupling. Putting these classes under a folder or a class library like BLL and DAL does not immediately result in software with clean architecture and good separation of concerns.

Despite that, my argument is that these folders (BLL and DAL) can and should reside in the main web project and moving them into a separate class library does not add any values. It doesn’t magically create layers in your applications.

There are 2 cases for splitting a project into smaller projects: reusability and independently deploying those projects.


One reason for separating a project into multiple class libraries is re-usability. I’ve yet to see the BLL or DAL part of a web application re-used in another application. This is what text books from 90s used to tell us! But most if not all modern applications are too specific and even in the same enterprise I’ve never seen the same BLL or DAL parts re-used across multiple applications. Most of the time what you have in those class libraries is purely to serve what the user sees in that particular application, and it’s not something that can be easily re-used (if at all).


Another reason for separating a project into multiple class libraries is about deployability. If you want to independently version and deploy these pieces, it does makes sense to go down this path. But this is often a use case for frameworks not enterprise applications. Entity Framework is a good example. It’s composed of multiple assemblies each focusing on different areas of functionality. We have one core assembly which includes the main artefacts, we have another assembly for talking to a SQL Server database, another one for SQLite and so on. With this modular architecture, we can reference and download only the parts that we need.

Imagine if Entity Framework was only one assembly! It would be one gigantic assembly with lots of code that we won’t need. Also, every time the support team added a new feature or fixed a bug, the entire monolithic assembly would have to be compiled and deployed. This would make this assembly very fragile. If we’re using Entity Framework on top of SQL Server, why should an upgrade because of a bug fix for SQLite impact our application? It shouldn’t! That’s why it’s designed in a modular way.

In most web applications out there, we version and deploy all these assemblies (Web, BLL and DAL) together. So, separating a project into 3 projects does not add any values.

Use Cases for Physical Separation

So, when do you actually need to physically separate a project into multiple projects? Here are a couple of scenarios:

1- Multiple presentation layers: Let’s say you’ve built an order processing application. This application is a desktop application used by staff at your organization. You decide to build a web interface for this application so the staff can access it remotely. You want to re-use the existing business logic and data access components. As I explained earlier, one reason for physical separation is re-usability. So, in this case, you need to physically separate this project into three projects:

  • OrderProcessing.Core (contains both the BLL and DAL)
  • OrderProcessing.Web
  • OrderProcessing.Desktop

Note that even here I don’t have two projects (BLL and DAL). I have one project, OrderProcessing.Core, that encapsulates both the business and data access logic for our order processing application.

So, why didn’t I separate this project into two separate projects (BLL and DAL)? Because the whole purpose of this DAL is to provide persistence for what we have in BLL. It’s very unlikely that it’ll be used on its own in another project.

Also, following the dependency inversion principle of object-oriented design, the dependency should be from DAL to BLL, not the other way around. So, this means, everywhere you reference the DAL assembly, you should also reference the BLL assembly. In other words, they’re highly cohesive and inseparable. When you separate things that are cohesive, you run into issues later down the track.

2- Multiple applications under a single portal: Another use case that one of the readers suggested is where you have multiple small applications that are hosted in a single portal. So, from the end user’s point of view these applications are not separate; they are all different domains of the same application. But from development point of view, each application is independent from the others. Each application can have its own persistence store; one can use Excel, another can use SQL Server, and the other can use Oracle.

In this scenario, it’s likely that these applications are developed by different developers/teams. They’re often independently developed, version and deployed, hence the second reason for physical separation.

For this scenario, we could have a solution with the following projects:

  • OrderProcessing.Core (a class library)
  • Shipping.Core
  • CustomerSupport.Core
  • MainPortal (an ASP.NET MVC project)

Once again, you don’t see the BLL/DAL separation here. Each class library (eg OrderProcessing.Core) includes both the business and data access logic for its own domain.

The Bottom Line

Here are a few things I hope you take away from this article:

  • Layers are not tiers.
  • Tiers are about physical distribution of software on different computers.
  • Layers are conceptual. They don’t have a physical representation in code. Having a folder or an assembly called BLL or DAL doesn’t mean you have properly layered your application, neither does it mean you have improved maintainability.
  • Maintainability is about clean code, small methods, small classes each having a single responsibility and limited coupling between these classes. Splitting a project with with fat classes and fat methods into BLL/DAL projects doesn’t improve the maintainability of your software.
  • Assemblies are units of versioning and deployment.
  • Split a project into multiple projects if you want to re-use certain parts of that in other projects, or if you want to independently version and deploy each project.


As always, keep it simple!

If you enjoyed this post, please share it with your friends.

Tags: , , ,

Announcing my upcoming Xamarin Forms course

I’m excited to let you know that I’ve recorded and edited 7.5 hours of high quality content for my upcoming Xamarin Forms course.

Xamarin logo

In this course, I’ll take you on a pragmatic and step-by-step journey and teach you how to build native mobile apps for Android, iOS and Windows using Xamarin Forms and C#.

In particular, you’ll

  • Learn and understand the fundamentals of Xamarin Forms and its architecture
  • Build user-interfaces with XAML and code
  • Work with images
  • Present data in beautiful, interactive lists
  • Implement multi-page apps with navigation, tabs, master/detail pages
  • Build form and setting pages
  • Store and retrieve data from a variety of sources (file system, SQLite database and RESTful services)
  • Implement Model-View-ViewModel (MVVM) architectural pattern

This course, just like my other courses is packed with real-world examples, exercises and best practices. Not only will you learn how to use Xamarin Forms, you’ll also learn first-class tips to make your code cleaner and more maintainable.

Lectures also have downloadable source code so you can code-along with me while watching the videos.



All you need to know in order to take this course is C#. At a minimum, you should be comfortable with classes, interfaces, events, delegates, lambda expressions and a bit of LINQ. If you struggle with any of these features, I highly recommend you to take my following C# courses to strengthen the fundamentals:

C# Classes, Interfaces and Object-oriented Programming

C# Advanced Topics

If you have any familiarity with XAML-based frameworks (such as WPF or Silverlight) it’s a bonus but not a requirement.


Get the course with a huge discount

The price for this going to be $150 but my subscribers can get it for only $20. If you’ve received this post in your mailbox, that means you are a subscriber. So you don’t have to do anything further. Otherwise, simply join my mailing list to get my upcoming Xamarin Forms and any of my other courses with big discounts.


Frequently Asked Questions

Do I need a Mac to take the course?

Not at all! You can use use Visual Studio on Windows to build and deploy apps to Windows and Android. You need a Mac only to build your app for iOS. And this involves simply adding a new project to your Visual Studio solution, setting it as the start up project and building it. That’s it! You don’t need to write any extra code.

So, no, you don’t need a Mac to take this course or learn Xamarin Forms in general.


Do I need to know about Xamarin.Android and Xamarin.iOS libraries?

Again, no! Xamarin Forms provides a simple, unified API for you to build cross-platform mobile apps. When you build your app for Android or iOS, it will internally use Xamarin.Android or Xamarin.iOS to map the common user interface elements to their corresponding native equivalent.

You need to know about Xamarin.Android or Xamarin.iOS only if you want to build custom user-interface elements.


When this course is coming out? I’m impatient and can’t wait! 

It’ll be live in mid September or a bit earlier.


So, if you want to get the course for only $20, join my mailing list now. Once the course goes live, I’ll send you an email with a coupon.



Tags: ,

Should you learn ASP.NET MVC 5 or ASP.NET Core 1?

A common question that I get a lot lately:

Mosh, I’m not familiar with MVC. I have some background in [ASP.NET WebForms, Classic ASP, etc]. Should I learn ASP.NET MVC 5 or ASP.NET Core 1?

A variation of this question is:

I’m confused about what to learn. What is the difference between ASP.NET MVC 5, ASP.NET MVC 6, ASP.NET 5 and ASP.NET Core 1?

So I thought to turn this into a short blog post.


ASP.NET Core 1 is the next version of ASP.NET MVC 5. Yes, the version number is confusing! It has gone through a few name changes. It started as ASP.NET vNext, then changed to ASP.NET 5, next was renamed to ASP.NET MVC 6 and eventually became ASP.NET Core 1.0. You’re not the only one frustrated about these name changes!

Scott Hanselman has explained the rationale behind these name changes perfectly in his post.

The Simple Answer

If you have little or no experience with ASP.NET MVC (any versions), and you’d like to learn it from me, your best source is my Complete ASP.NET MVC 5 course.

ASP.NET Core 1 is based on the same principles you learn in that course. More than 90% of what you learn is the same in the new ASP.NET. There are some improvements in the framework and the tooling. None of these are revolutionary! You can get up to speed with them by reading a few tutorials or watching a few videos. I’m planning to create a short (1 – 2 hour) course that helps developers with knowledge of ASP.NET MVC 5 transition to the new ASP.NET.

Having said all that, in my opinion, ASP.NET Core 1 is not quite production yet. There are still hiccups with Entity Framework 7 and unless you work in a very adventurous team, most teams and projects out there are based on ASP.NET MVC 5 or earlier.

Hope that answers your question.

Tags: , , , ,

Why coders should work 5 hours a day!

I have a strong opinion:

Programmers should work 5 hours a day.

Without knowing you or the kind of projects you’re working on, I can guarantee that 80% of what you deliver in a given day comes from the first 5 hours of your day. In fact, most likely within the first 3 – 4 hours, before your lunch break.

If I had a software development company and I was to employ you, I’d pay you the same salary as someone working 8 hours a day, but you’d work only 5 hours a day. I’d let you go home and enjoy whatever you like!

Unfortunately, despite living in the modern era, our workplace is still following a traditional system: the typical 9 to 5 working hours. While this may work for many industries, I don’t find it optimum programmers.

You’re at risk for RSI

There was a time I used to code for 12 hours a day, sometimes including weekends! Guess what happened? I started to feel pain in my wrists. Many know this as Carpal Tunnel Syndrome, which falls under Repetitive Strain Injuries (RSI) umbrella term.

My pain started in my wrists, and then travelled to my palms and forearms. At some point, I was in so much pain that some days I could only code for 1 or 2 hours and then I had to leave work. I used to be a contractor, so leaving work meant I was not getting paid! You can imagine how stressful this was, which made my pain even worse. Plus, coding has been one of my passions and thinking that I could not code like before was very depressing.

A lot of programmers develop this kind of pain at some point in their life. Some (like me) manage to recover (not 100% though), but for others, this remains a challenge for the rest of their life.

Many others develop pain in their forearms, neck, shoulders or lower back. All this can be due to stress, bad posture and working long hours without having regular breaks.

A simple solution

So, now you know that as a coder, you’re at risk for pain in your wrists, forearms, neck, shoulders and lower back. And you also know that most (if not all) companies out there still follow the traditional 9 to 5 system. So, what can you do to keep a healthy body?

Code for 45 minutes and then have a 5 – 10 minute break

Not only will this prevent you from developing all sorts of pains due to excessive use of keyboard, but it’ll also help you increase your productivity significantly.

Now, this formula sounds pretty simple but there are exceptionally few programmers who actually practice it. I personally think perhaps 1 out of 100 programmers take regular breaks when coding, maybe even fewer! But why?

I’m going to list a few “excuses” that most programmers give for not taking regular breaks. Read and see if you can relate to them.

Excuse 1: My employer thinks I’m wasting time

If your employer has problem with you taking a 10-minute break every 45 minutes, you need to look for a different job. I’m dead serious! Do you care about yourself and your body? If you’re reading this post up to this point, you certainly do.

You either need to educate your employer or leave them. Taking regular breaks not only helps you maintain a healthy body, but it also increases your productivity significantly. All this means, as an employee, you’ll perform better for that employer. You’ll write better code in less time. So, your employer should in fact encourage you to take frequent breaks.

Send this blog post to your manager and peer programmers and try to establish this culture in your company so everybody get up and have a 5 – 10 minute together. Make it fun. You can start work at 9am and have a break at 9:45am. Everybody gets up, do a few stretches or go for a short work.

Remember, break means detox from technology. If you’re still sitting at your desk but browsing Facebook on your PC or mobile, you’re not on a break. Get up and go for a short walk around the block. You’ll feel 10 times better when you get back.

Excuse 2: I’ll lose focus if I have a break

You won’t! It’s all in your head. When you leave your desk and go for a short walk or something else, your subconscious mind is still working on the problem even if you’re not actively thinking about it. When you get back to your desk, you’ll be fresh and ready to do another 45 minutes of ninja coding.

Also, just before leaving your desk, you can write down the stuff you want to remember. That helps too.

Excuse 3: I forget to have a break!

I can totally relate to you on this. It’s quite easy to lose track of time when you’re coding. The simplest solution is to set a timer on your phone.

You should discipline yourself, so as soon as you hear the alarm, you get up and leave your desk. Do NOT say to yourself: “No, I’m going to finish this in a minute and then I’ll go”. That one minute becomes five minutes and then eventually becomes hours.

So, one more time: discipline yourself so the moment you hear the alarm, you get up and leave your desk.


Share your thoughts

What are your excuses for not taking regular breaks? Share them in the comments section and I’ll see if I can help you with them.

Did you enjoy this post? Please share it with your colleagues and friends.



[Q&A]: What is the difference between junior and senior developers?

I’m excited to announce that I just published the first episode of my Q&A shows on YouTube. In this episode, I’ve answered Kyle’s question:

What is the difference between junior and senior developers?

If you enjoy this video, please like and share it. If you want me to include your question in my upcoming shows, please use the comments section on YouTube. You can ask me anything, technical or non-technical.


Ask me anything in my YouTube shows

I’ve been thinking about producing weekly YouTube shows to help you with what is stopping you from achieving your aspirations. These shows are in the form of questions and answers. You send me your questions (by filling out the form below), and in each show I’ll pick a few questions and talk about them.

You can ask me ANYTHING (technical or non-technical), except the following:

  • Code not compiling or ​running on your machine
  • Exceptions you get at run-time

I don’t answer questions like that because I believe a programmer must be able to isolate and troubleshoot such issues on their machine themselves.

If you don’t learn the skills to troubleshoot such problems yourself, you’re going to have a difficult time working as a full-time software developer. Every single day you’re going to face such issues and I’m not there to help you. You cannot ask your colleagues for help every single time either. Your only resource is Google and try and error.

When I was a junior programmer, I didn’t even have Google. I used to stay up till 4am troubleshooting these problems. I had to comment out the code line by line, and look into exact locations of memory (talking about C++ and assembly back then) to find out what was happening. These days, you don’t have to do that. If you spend only 2 minutes, most of the time, you’ll find your answer on the first link on the first page of Google search results.

So, feel free to ask me any technical or non-technical questions. Your non-technical questions can be on topics such as getting a job, or if you have a job, you may have some challenges at work (e.g. collaborating with others especially strongly-opinionated developers in the team, etc). You may suffer from RSI (repetitive strain injuries), etc.

So, if you like me to answer your questions as part of my weekly shows, simply feel out the following form.

I love to hear about you, your aspirations and your challenges. Feel free to write as much detail as you want. This helps me better understand you and come up with proper advice in my shows.​​​



My upcoming courses in this year

Just wanted to say a quick thank you to every one who filled out my little survey. The top most voted courses are:

  • Design Patterns
  • Building iOS and Android Apps with Xamarin
  • Advanced Angular 2

So these are the courses that I’ll be focusing on for the next few months. Of course, this is not a definite plan and sometimes unexpected things happen and I may have to focus on a different topic.

I don’t have a firm decision about which course I’ll be publishing next, but for the moment, I’m leaning more on Xamarin. 



Update on my Pluralsight course

I’ve been getting a lot of emails lately, almost on a daily basis, people asking me when my Pluralsight course (Building a Real-world App with ASP.NET MVC) is going to get published and how it is different from my upcoming ASP.NET MVC course on Udemy.

So, I’m going to answer these two questions in this post.

Udemy course

This course will teach you the fundamentals of building web apps with ASP.NET MVC 5. I’m aiming to publish it in 2 weeks or less. Here is a sneak peak of what you’re going to get.

Is this the same as the Pluralsight course? Yes and no. There are some overlaps, but they have differences. In the Pluralsight course, I don’t really teach much of the ASP.NET MVC framework. I’m assuming you have some basic familiarity and want to learn how to build a real-world app end to end.

In the Udemy course, I assume you know nothing about ASP.NET MVC and I teach you all the details step-by-step.

And here is more about the Pluralsight course.


Pluralsight course

This course is about 15 hours long, distributed over 3 parts. Almost 95% of the course is reviewed and approved by Pluralsight and we’re aiming to finish it off in less than 2 weeks. But I can’t promise anything because once I fully hand it off to Pluralsight, it’s up to them to decide when they’ll publish it, but I can’t think of a reason why they would want to hold on to that.

By the way, I decided to rename the course from “Building a Real-world App with ASP.NET MVC” to “Become a Full-stack .NET Developer“, because I realized that is really the core of what I teach in this course. It covers a wide range of front-end and back-end skills.

The application I’ve built over these three parts is a simplified social networking app for live gigs. Artists can sign up and list their upcoming gigs. Users can follow artists and get upcoming gigs in their gig feed. If a gig is updated or removed, they’ll receive a notification, similar to Facebook notifications.

Here are more details about each part.

Part 1: Fundamentals

Part 1 is for junior developers who have basic familiarity with ASP.NET MVC and Entity Framework. This is mostly for people who know a little bit of these technologies but don’t know how to put them together and build a real-world application. I’ve received tons of emails from students telling me they don’t know how to start from the requirements document, how to go from one step to the next, how to version their code, etc. So, that’s the essence of this part.

I’ll also talk about security, usability and building beautiful user interfaces using HTML and CSS.

Part 2: Advanced Concepts

Part 2 is for the intermediate developer and includes more advanced use cases. This is where I’ve implemented the Facebook-like notification system. There is a lot of emphasis on domain modelling and object-oriented design in this part. You’ll also learn about refactoring an anaemic domain model (which is a common issue in design of many applications out there) into a behaviour-rich domain model.

Part 3: Architecture and Unit Testing

Part 3 is what takes you from an intermediate developer to an advanced developer. In this part I talk about

  • Refactoring spaghetti JavaScript code
  • Repository and unit of work patterns
  • Programming against interfaces
  • Dependency injection
  • Clean architecture
  • Unit testing
  • Integration testing

This course is packed with concepts, best practices and keyboard shortcuts and I’m sure you’re going to love it.

Pluralsight’s feedback

This morning I woke up with a sweet email from Pluralsight giving me feedback about my course. I was in bed reading the email with one eye and within a few seconds both my eyes were big open and I couldn’t not smile. So I thought to share the feedback with you.

You are a meticulous coder! The spacing, alignment, various conventions, even alphabetical order of things–all awesome

Nice sample app. It’s simple enough to be approachable, but still robust enough to show important concepts, and it feels like a real-world app that I might build.

Clean, crisp audio, good volume. Nice work on recording/editing.

I like your approach of implementing things in an “ugly” way, then showing how to make them better. I think this is a great way to learn; it’s much more effective than showing only the “correct” way up front.

You did a nice job talking through the keyboard shortcuts you were using throughout the demos. Very helpful.

Loved your story about John throwing code wherever with a 5-second approach, then realizing it’s a mess, then implementing with a shiny new framework. I can’t tell you how often I’ve seen this happen!!!

I like that you acknowledged that some developers find testing to be painful and time-consuming. I think this gives you credibility, and shows that you aren’t selling some unrealistic “rainbows and butterflies” view on testing.

Great explanations of IIFE/revealing module pattern.

As much as you’ve been excited to watch this course, I’ve been excited to share all this with you and can’t wait until it goes live. So, if you’ve not joined my mailing list, be sure to join now and I’ll send out an announcement once the course is live.

Tags: , ,

Angular 2 Tutorial: Angular 2.0 in 20 minutes

This article is outdated. Check out my brand new Angular 4 tutorial on YouTube.

Angular 2 has been getting a lot of momentum lately. The number of tweets and posts have been increasing as Angular team have been preparing the release candidate. So, I’m planing to write a series of hands-on blog posts to help you get started with Angular 2.0. If you have any questions as you read this article, please drop a comment below. I’ll answer every question and update the post if required.

Whether you’re familiar with Angular 1 or not, it doesn’t matter. You just need to have basic familiarity with HTML, CSS and Javascript.

Let’s start by a few beginners’ questions.

Beginners’ questions

If you’re already familiar with Angular 1, feel free to skip this section.

What is Angular? 

Angular is one of the leading frameworks for building well-structured, testable and maintainable front-end applications. It’s often (but not necessarily) used in building single page applications (SPAs).

Why do I have to learn Angular?

Angular is not the only framework for building modular, testable and maintainable front-end applications. There are many other frameworks and libraries out there, including but not limited to React, Ember, Backbone, etc. Do you have to learn them all? If you have time and passion, why not! But if you have limited time, you may better invest your time in learning Angular 2.0 and React as these are the leading frameworks in this space.

Angular is developed by Google and has a huge community support. Google trends shows that the demand for Angular developers is increasing constantly.

angular developer

So, whether you’re an aspiring or an established front-end or full-stack developer, knowing how to build applications with Angular can definitely increase your options when it comes to finding that ideal job.

Is Angular better than “…”?

The problem with this kind of question is that it’s hard to define “better”. Every framework has certain strengths and weaknesses. Religious debates about which framework is “better” than the others are really useless and don’t give you any values.

So, instead of wasting your time researching the best framework out there, spend some time and learn the top 2 – 3 leading frameworks. Then, you can pick the one that works best for you.

Getting the tools

If you don’t have Node on your machine, first, head over to and download and install the latest version of Node.

Once you install Node, open up Command Prompt on Windows or Terminal on Mac, and run:

npm install -g typescript

If you are a Mac user, you need to put sudo before npm to run this command with administrative privileges.

This will install TypeScript globally on your machine. TypeScript is a superset of Javascript and is the language we will be using in this tutorial. Why TypeScript? Because it brings many useful features to Javascript that are missing in the current version of Javascript, including classes, interfaces, access modifiers (e.g. public, private), IntelliSense and more importantly compile-time checking. So, we can catch many programming errors during compile time. Angular 2.0 itself has been written with TypeScript.

Just note that browsers don’t understand TypeScript. We use TypeScript compiler to compile or more accurately transpile TypeScript into Javascript. More on this later.

Next, run:

npm install -g typings

Typings is another Node module that we use to reference existing Javascript libraries in TypeScript.

Finally, you need an editor. You can use any editors that support TypeScript, including VSCode, Sublime, Atom, IntelliJ IDEA, Visual Studio and etc.

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 component of 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 to http://localhost:3000. This is our first Angular 2.0 app.


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';

    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:

    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 of AppComponent and render it (according to its template) inside that element. Open up index.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.

    selector: 'my-app',
    template: `
<h1>Hello {{title}}</h1>

Now, add a button and a span to the template:

<h1>Hello {{title}}</h1>
<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";


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.

If you enjoyed this tutorial, please drop a comment below and share it with others.

You can also check out my comprehensive Angular 2 course here.

logo draft 2_3_2048