Comments

Angular 4 Tutorial: Angular 4 in 20 minutes

So, do you want to learn the fundamentals of Angular 4 in a quick and easy way? You have come to the right place! You don’t need familiarity with any previous versions of Angular. In this tutorial, I’m going to take you from the ground up and show you Angular 4 in action. You only need a basic familiarity with HTML, CSS, and JavaScript.

If you learn better by videos, you can also watch this tutorial on YouTube; otherwise, continue reading.

Beginner’s questions

Let’s start with a few beginner’s questions. If you’ve used any previous versions of Angular, feel free to skip this section and jump to “Getting the tools”.

What is Angular?

Angular is a framework for building client applications in HTML, CSS, and either JavaScript or a language like TypeScript that can be compiled (more accurately, transpiled) to JavaScript. If you have never worked with TypeScript before, don’t worry. I will give you the basics in order to complete this tutorial.

What is TypeScript?

TypeScript is a superset of JavaScript. That means any valid JavaScript code is valid TypeScript code. But many prefer TypeScript because it has additional features that we don’t have in the current version of JavaScript that most browsers understand. So, when building Angular applications, we need to have our TypeScript code converted into JavaScript code that browsers can understand. This process is called transpilation which is the combination of translate and compile. And that’s the job of  the TypeScript compiler.

Why do I need a framework like Angular?

A common question a lot of beginners ask me is: “Why do we need Angular in the first place? What’s wrong with the plain old vanilla JavaScript and jQuery?”.

There is nothing inherently wrong with using vanilla JavaScript/jQuery. In fact, a lot of web applications out there are built this way. But as your application grows, structuring your code in a clean and maintainable and more importantly, testable way, becomes harder and harder. I’m not saying this is impossible. But using a framework like Angular, makes your life far easier. Sure, there is a learning curve involved, but once you master Angular, you’ll be able to build client applications faster and easier.

Is Angular better than React/Vue.js?

These days there is a lot of debate between Angular vs React vs Vue.js. Whether Angular is better than React or Vue.js depends on how you define “better”. Each of these frameworks have strengths and weaknesses and there is no one shiny framework that makes every developer in the world happy. My suggestion to you is to learn the fundamentals of each of these frameworks and choose the one that works best for each project depending on its requirements.

Getting the tools

Now, let’s get dive into some code and get our hands dirty! The first thing you need to install is the latest version of Node. So, if you haven’t installed Node, head over to nodejs.org, and install the latest stable version.

Node comes with a tool called Node Package Manager or NPM, which is used for installing third-party libraries. In this tutorial, we’re going to use NPM to install Angular CLI. That is a command-line tool we use to create a new Angular project. It is also used for generating some boilerplate code during development (such as components, services, etc) as well as building an application for deployment. We do all this in the terminal.

So, once again in the Terminal, run the following command to install Angular CLI:

npm install -g @angular/cli

The -g flag stands for global. If you don’t put -g here, Angular CLI will be installed only in the current folder, and it’s not going to be accessible anywhere else.

If you’re on Mac, you need to put sudo at the beginning of this command to execute it as an administrator; otherwise, you’ll get permission errors.

Your First Angular App

So with Angular CLI in place, now we can create a new Angular project using the following command:

ng new hello-world

As you can see, we can access Angular CLI using ng. We provide a command (in this case new) to instruct Angular CLI on what we want it to do for us. Here, we are telling Angular CLI to generate a new project called “hello-world” and store it in a folder with the same name. We’ll be looking at these generated files shortly. For now, let’s finish the first step and see our new Angular app in the browser.

So, run the following commands in the terminal:

cd hello-world
npm install 
ng serve

With the second command (npm install) we install all the dependencies of our application. The last command (ng serve) compiles our application and hosts it using a lightweight web server. Now, we can access our application at http://localhost:4200. 

So, open up your browser and navigate to this address. You should see the following page:

Congratulations! You generated and served your first Angular 4 application. Now, let’s have a quick look at the files and folders in our new Angular project.

Structure of Angular Projects

Inside the generated folder, you’ll find the following top-level folders:

  • e2e: includes end-to-end tests.
  • node_modules: all the third-party libraries that our project is dependent upon.
  • src: the actual source code of our Angular application.

99.9% of the time you’ll be working with the files inside the src folder. But let’s quickly overview the other files we have in this project:

angular-cli.json: a configuration file for Angular CLI. We use this file to import third-party stylesheets or define additional environments (eg testing environment) for our application.

package.json: a standard file for Node-based projects. It contains metadata about our project, such as its name, version as well as the list of its dependencies.

protractor.conf.js: Protractor is a tool for running end-to-end tests for Angular projects. We hardly need to modify this file.

karma.conf.js: Karma is a test runner for JavaScript applications. This file contains some configuration for Karma. We rarely need to modify this file.

tsconfig.json: includes setting for the TypeScript compiler. Again, we hardly, if ever, need to modify this file.

tslint.json: includes the settings for TSLint which is a popular tool for linting TypeScript code. That means it checks the quality of our TypeScript code based on a few configurable parameters. This is especially important in a team environment to ensure that everyone follows the same conventions and produces code of the same quality. We can run linting on our code using Angular CLI in the terminal or we can add it to our editor as a plug-in.

So, as you see, all these files are configuration files that work smoothly out of the box. Unless you want to customize them for your specific environment, you don’t ever have to modify them.

Architecture of Angular Apps

Ok, so you’ve learned how to generate and serve a new Angular project. You’ve also learned about various files and folders in a new Angular project. Now, let’s look at the architecture of Angular applications.

The most fundamental building block in an Angular application is a component. You can think of a component as a view component. It represents a view or part of a view (what the user sees). A component consists of three pieces:

  • HTML markup: to render that view
  • State: the data to display on the view
  • Behavior: the logic behind that view. For example, what should happen when the user clicks a button.

 

A component can contain other components. For example, let’s imagine you’re going to build a web app like Twitter using Angular. In your implementation, you may have a tree of component likes this:

  • App
    • NavBar
    • SideBar
    • ContentArea
      • Tweets
        • Tweet
          • Like

 

Now, at the root of the application, we have a component called AppComponent. This is the root of every Angular application. Our AppComponent contains 3 child components: NavBar, SideBar, and ContentArea.

The reason for such separation is because the navigation bar is logically a separate part of the view. It has its own markup, state, and behavior.  We can encapsulate all that using a component called NavBarComponent. This way, when modifying or extending the navigation bar of our application, we can focus on a small component with a lightweight template.

Benefits of Component-based Architecture

As you can see, this component-based architecture makes our applications more organized and maintainable. Plus, we can potentially reuse these components in various parts of an application or in an entirely different application. For example, tomorrow, we can grab this NavBarComponent and put it in an entirely different project. We just need to modify the links. But all the HTML markup will remain the same.

Back to our tree of components, you can see that inside the content area, we have a tree of components like this:

  • Tweets
    • Tweet
      • Like

Again, this is one way to model this. We don’t necessarily have to have a separate component for the list of tweets and each tweet. We could combine TweetsComponent and TweetComponent into one component. But, I’d like to separate the LikeComponent because we could potentially reuse this like button somewhere else in this application or in another application. Even if we don’t reuse it, separating the markup, state and behavior of this like button into a separate component, makes our application more maintainable and testable.

An Angular Component in Action

Now, let’s inspect a real component in action.

Back to our project, open up the src/app folder. Inside this folder, you should see the following files:

  • app.component.css
  • app.component.html
  • app.component.spec.ts
  • app.component.ts
  • app.module.ts

 

These files represent AppComponent, which is the root component for our application. In this particular case, all these files are inside the app folder. But when we generate a new component using Angular CLI, all the files that make up a component will be grouped by a folder.

So, in terms of the implementation, each component in an Angular project is physically implemented using four files:

  • A CSS file: where we define all the styles for that component. These styles will only be scoped to this component and will not leak to the outside. This is what Shadow DOM does. But not all browsers today support Shadow DOM. So, Angular uses a technique to emulate the Shadow DOM.
  • An HTML file: contains the markup to render in the DOM.
  • A spec file: includes the unit tests.
  • A TypeScript file: where we define the state (the data to display) and behavior (logic) of our component.

You will also see an app.module.ts file.  This file defines the root module of our application and tells angular how to assemble the app.

 

Creating a Component

Now that you know what a component is, let’s use Angular CLI and add a new component to this application.

Imagine we want to build an e-commerce application. On the home page, we’re going to display the list of products and below each product, we want to have a button for adding that product to the shopping cart.

So, for this exercise, we want to create a super simple component to represent each product on the home page. This component will include the HTML markup to display that product, and it’ll respond to the click event of a button to add that product to the shopping cart.

When we click this button, it also shows the number of products of this type in the shopping cart. Initially, the number should be 0. Every time we click the Add to Shopping Cart button, the number is increased. Of course, in a real-world application, there’s far more complexity involved. For example, we may want to call some back-end services to store this item in a database. But for now, let’s just focus on the fundamentals. If you understand the fundamentals well, you can always add these other details later. So, for now, forget about the server-side, databases and other complexities.

Ok, we’re ready to create a component. We can manually create all those four files by hand, but there is a faster way. We can use Angular CLI!

Generating a Component Using Angular CLI

Run the following command in the terminal, inside the project folder:

ng g c product

Here, g is short for generate, c is short for component and product is the name of our component. Now, if you look at the project folder, inside the src/app folder, you should see a new folder called product. Expand this folder. You should see the following files:

  • product.component.css
  • product.component.html
  • product.component.spec.ts
  • product.component.ts

Open product.component.ts. This is what you should see:


import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  constructor() { }

  ngOnInit() { 
  }

If this code looks complex to you, don’t worry! I’m going to make it super simple. It’s actually far easier than you may think!

For now, I want you to note the value of the selector property. It’s app-product. This is a CSS selector. So app-product represents an element by this name. With this, we can extend the HTML vocabulary. Anywhere we add this app-product element, Angular will render the HTML markup of ProductComponent inside that element. So, let’s add this element to the template for our AppComponent.

Using a Component

Open up src/app/app.component.html. Replace all the markup with the following:

<app-product></app-product>

Now, our application includes a tree of components:

  • App
    • Product

At the root of this tree, we have our AppComponent. This component includes a child component: ProductComponent. 

Save the changes. Back to the browser, now, you should see this:

Our ProductComponent has a simple template that includes “product works!”. We can modify product.component.html and add some complex markup here. For example, we can use Bootstrap 4 cards to render the product inside a card.

But for now, we don’t want to waste our time and make our application pretty. Our focus is on understanding Angular. We can always come back to the template for ProductComponent and improve it.

Examining an Angular Component

You successfully generated and used a component. Now, let’s examine this component in detail. So, open up product.component.ts. Here is the code for reference:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  constructor() { }

  ngOnInit() { 
  }

Inside of this file, we have a TypeScript class called ProductComponent.

What is a Class?

A class is a fundamental building block of many object-oriented programming languages. It’s a container for a bunch of related functions and variables.

So, unlike vanilla JavaScript where all our functions and variables are hanging from the global namespace, we put them in containers called classes. With these classes, we don’t pollute the global namespace and as a result, we won’t have one function overwriting another function with the same name. Because these functions are now in separate containers (classes). Also, because each class includes a bunch of highly related functions and variables, our code is more organized and maintainable.

In object-oriented programming terms, we call these functions and variables that reside in a class, methods and fields/properties respectively. Fields and properties are technically different but they are often used interchangeably. A field is like a variable where we store some data. A property looks like a field from the outside, but internally, it is a function around a field that gives us read or write access to that field. If this sounds confusing, don’t worry about it now. I’m planning to publish a separate post about TypeScript. For now, you can assume fields and properties are the same, even though they are not!

Example of a Class

So, in product.component.ts, we have a class called ProductComponent. This class has 2 functions (methods): constructor and ngOnInit.

export class ProductComponent implements OnInit {
  constructor() { }

  ngOnInit() { 
  }

Constructor is a reserved keyword in TypeScript. A method by that name is a special method in a class. This method is called automatically when we create an instance of that class.

ngOnInit is a special method in Angular. Angular calls this method when it creates an instance of this component and displays it to the user in the browser.

For this exercise, we don’t have to worry about either of these methods. So, delete both of them. You should also delete implements OnInit in front of the class name. For now, don’t worry about it, but basically, it tells Angular that this class has some initialization code that should be executed before this component is displayed to the user.

So, your code should look like this:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent {
}

Component Metadata

So, you’ve seen that we implement a component using a TypeScript class. But a class on its own is just a class. It only includes some data and logic for a view. It doesn’t include any HTML markup or CSS styles. In order to attach these to this class, we need to promote this class to a component. We can do this by using the @Component() decorator function on top of this class (lines 3-7):

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent {
}

With this, we can attach metadata to this class that Angular understands. This @Component() decorator function is defined in Angular and you can see we’re importing it on line 1. It takes an object with the following properties:

  • selector
  • templateUrl
  • styleUrls

You’ve seen the selector in action. It associates a new HTML element to this component. With this, we can extend the standard HTML vocabulary. So, now we have a new custom element (app-product) that we can use anywhere in our application. When Angular sees that element, it’ll place the HTML markup of our ProductComponent inside that element.

The other 2 properties (templateUrl and styleUrls)  are self-explanatory. They specify the path to the HTML template and CSS file(s) for this component.

Property Binding

In Angular, unlike vanilla JavaScript or jQuery, we don’t work directly with the DOM. So, we don’t write code like this:

$("#myElement").text("something")

Instead, we use property binding. Let me show you how that works.

In our ProductComponent, let’s add a new field:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent {
   title = 'USB Stick 8GB';
}

This title field contains the title for our product. In a real-world scenario, we get this title from a database somewhere on the server. So we don’t hardcode it here. But for now, let’s not worry about this and see property binding in action.

Now, open up product.component.html. Replace all the markup there with:

<p>{{ title }}</p>

This special double curly brace syntax you see here is what we call interpolation in Angular. Fancy name again, right? This basically tells Angular to replace what we have between curly braces with the value of the title field in our component.

This syntax is a shorthand for the actual property binding syntax we have in Angular. The code you wrote above is equivalent to the following code:

<p [innerHtml]="title"></p>

What is this? Very simple! In vanilla JavaScript, we can simply get a reference to an element in the DOM and set its innerHTML property like this:

var el = document.getElementById("myElement");
el.innerHTML = "USB Stick 8GB";

So, every DOM element has a property called innerHTML. In our Angular application, we’re using the square bracket syntax to bind a property of a DOM element to a field/property in our component:

<p [innerHtml]="title"></p>

So, at run-time, Angular will set the innerHtml property of this paragraph to the title field we defined in our component. And more importantly, if the value of our title field changes in the future, Angular will automatically update the view (DOM) for us! This is property binding in action. We have bound the innerHTML property of this element to the title field of our ProductComponent.

A Simple Exercise

Now, here is a simple exercise for you. I want you to extend our product component and display the number of USB sticks in the shopping cart below the name of this product. So, stop reading and make any necessary changes in the code. Then, come back here and see my solution.

Ok, so you should have added a new field in ProductComponent:

export class ProductComponent {
   title = "USB Stick 8GB";
   itemCount = 0; 
}

And used interpolation or property binding syntax to render it in the template:

<p>{{ title }}</p>
<p>{{ itemCount }}</p>

Event Binding

Similar to property binding, we have another concept in Angular called event binding. With property binding, we bind properties of DOM elements to fields/properties in our component. With event binding, we bind events of DOM elements (such as clicks) to methods in our component. So, for example, when the user clicks on a button, a method in our component will be called.

We’re going to extend our product component and add a button to increase the number of USB sticks in the shopping cart. So, modify product.component.html as follows:


<p>{{ title }}</p>
<p>{{ itemCount }}</p>
<button (click)="addItem()">Add</button>

Note the difference between property and event binding syntax. We use square brackets for property bindings and parenthesis for event binding. With this code, whenever our button is clicked, Angular calls the addItem() method in our component.

So, let’s implement this method in our component. Open up product.component.ts:

export class ProductComponent {
   title = "USB Stick 8GB";
   itemCount = 0; 

   addItem() { 
      this.itemCount++;
   } 
}

Here, we’re simply incrementing the itemCount field. Now, save the changes and go back to the browser. Test this application by clicking the Add button. You can see the count gets updated immediately. This is the beauty of property and event binding in action!

As I explained, Angular watches our itemCount field. When its value gets changed, Angular updates the DOM immediately.

What you’ve seen far is just the tip of the iceberg. There is far more to property and event binding and Angular in general. It’s impossible to cover it all in one blog post. If you’re serious about learning Angular, I have a complete course with 30 hours of high-quality videos. This is equivalent to a book with more than a thousand pages!

Recap

Let’s quickly recap what you’ve learned in this post:

  • Angular is a framework for building client apps with HTML, CSS and TypeScript.
  • It gives our applications a proper, maintainable and testable structure.
  • At the core of every Angular application, we have a tree of components.
  • Each component encapsulates the state (data), the HTML markup and the behavior for a view.
  • At a minimum, a component is implemented using a class. This class may include a bunch of fields for displaying data and methods, which will be called in response to events raised from the DOM events.
  • A component may have an external template stored in a separate HTML file.
  • It may also include one or more external stylesheets.
  • A component also has a selector. That tells Angular where in the DOM to place this component.
  • We use the property binding syntax (square brackets) to bind properties of DOM elements to fields/properties in our components.
  • When the value of these fields/properties change, Angular automatically updates the DOM (view).
  • We use the event binding syntax (parenthesis) to bind events of DOM elements to methods in our component.
  • Angular automatically calls these methods to handle events raised from the DOM elements.

 

Once again, if you want to learn everything about Angular from the basic to the advanced topics, I encourage you to enroll in my complete Angular course. This is far easier and faster than jumping from one tutorial to another. With this course, you can learn all these concepts in one place, step-by-step and you’ll build and deploy real e-commerce app with Angular and Firebase at the end of the course.

 

If you’ve enjoyed this tutorial, please show the love by sharing it with others. Thank you!

 

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags:
Comments

6 Essential VSCode Extensions for Angular Developers

In this post, I’m going to list my top favorite Visual Studio Code (VSCode) extensions for building Angular applications. If you know a great extension that is missing here, please let us know using the comment box below the post.

Installing an Extension

If you know how to install an extension in VSCode, feel free to skip this section. Otherwise, launch VSCode, and open the Extensions tab from the left side bar. Here, you can see the list of installed extensions. You can also search for other extensions. Once you find an extension, simply click the Install button. Then, reload VSCode and you’re good to go.

TypeScript Hero

This is by far my absolute favorite extension! You no longer have to manually import types in TypeScript. TypeScript Hero automatically imports the types for you as you write code. When pasting some code from somewhere else, you can also add all the missing import statements in one go!

Another useful feature of this extension is that it allows you to sort and remove the unused import statements. You also get code completion and several other useful features. Highly recommended!

Angular Language Service

This extension provides a rich editing experience for Angular templates. Imagine you have a field in your component as follows:

course = { 
   title: 'The Complete Angular Course', 
   author: { 
      name: 'Mosh Hamedani'
   }
} 

With this extension, you’ll get auto-completion in your HTML templates:

Autocompletion

Bracket Pair Colorizer

This extension allows matching brackets to be identified with colors.

Bracket

Move TS

As your application grows, you may want to break it down into smaller and more maintainable modules. You’ll have to move files and folders around. But what happens to all your import statements? They break! So, that’s what this extension is for. With Move TS extension, you can simply move files/folders around and this extension will automatically update your import statements.

Material Icon Theme

Do you like to have pretty icons in the project explorer? Install this extension!

Angular TypeScript Snippets

Another useful extension developed by John Papa that boosts your productivity when building Angular applications. It gives you a bunch of code snippets that allow you to quickly generate code. There are snippets for creating a component, service, directive, etc. You may argue that now we can easily create these artifacts using Angular CLI and that is absolutely right. However, this extension gives you some useful HTML snippets as well:

Angular TypeScript Snippets

You can find the complete list of snippets provided by this extension here.

What is your favorite extension that you frequently use? Use the comment box below and let us know.

If you enjoyed this article, please share it with others.

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: ,
Comments

Common Angular Errors

In this post, I’m going to list the most common errors you may encounter while getting started with Angular. For each error, I’m going to explain what it means and how to solve it.

This post is a work in progress and I’m planning to add more errors. If there is an error you encounter often, please let us know by dropping a comment.

Error 1: ‘ng’ is not recognized

When creating a new project with Angular CLI, you may receive the following error:

'ng' is not recognized as an internal or external command.

This error is simply telling you that Angular CLI is either not installed or not added to the PATH. To solve this error, first, make sure you’re running Node 6.9 or higher. A lot of errors can be resolved by simply upgrading your Node to the latest stable version.

Open up the Terminal on macOS/Linux or Command Prompt on Windows and run the following command to find out the version of Node you are running:

node --version

If you’re running an earlier version of Node, head over to nodejs.org and download the installer for the latest stable version.

Once you have installed Node 6.9+, you need to install Angular CLI globally:

npm install -g @angular/cli

Note the -g flag here. This tells NPM that you want to install this package globally so you can run it from any folders on your machine.

Error 2: node_modules appears empty

When you run ng serve, you may receive the following error:

node_modules appears empty, you may need to run `npm install`.

Our Angular applications use a bunch of 3rd-party libraries. These libraries are stored in the node_modules folder inside your project folder. When you create a new project using Angular CLI, these third-party libraries should be installed automatically. However, if you’re using a corrupted or a buggy version of Angular CLI, these libraries are not installed. So, you need to manually install them.

To solve this error, run npm install from the project folder. This command will look at package.json in your project folder. This file includes the list of dependencies of your project. NPM will download and store these dependencies in the node_modules folder.

 

If you found this post helpful, please share it with others.

If there is an error you’d like me to add to this post, please let me know using the comment box below.

Also, if you want to learn Angular properly from basics to the advanced topics, check out my complete Angular course.

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags:
Comments

Layered Architecture in ASP.NET Core Applications

One of the viewers of my YouTube channel asked me an interesting question. He mentioned in a typical layered architecture, he sees ASP.NET MVC building blocks (Controller, View, and Model) as part of the presentation layer. These days, however, a lot of modern applications are built with Angular/React on the client and ASP.NET Core (Web API) on the server. So, what is the presentation layer in this kind of architecture? Let’s see!

With this stack, we have the following layers:

  • Presentation
  • Service
  • Business Logic/Application Core
  • Data Access/Persistence

Presentation Layer

Your Angular components, their templates, and the models you define in your Angular app are all presentation layer artifacts.

Service Layer

The confusing thing about this layer is that the term “service” is overloaded and it means different things to different people. In the context of a layered architecture, it wraps an application and exposes the application functionality in terms of a simple API that the user interface can talk to. This is the classic definition. Think of it as the glue between the presentation and business logic layers.

Now, in our modern stack, our logical service layer is physically composed of two parts: one part is on the client (Angular HTTP services) and the other part is on the server (ASP.NET Core controllers). These Angular services and ASP.NET Core controllers are very cohesive. The methods on these services (eg CourseService.getCourses()) talk directly to the endpoints exposed by your ASP.NET Core controllers.

Business Logic Layer

In your ASP.NET Core controllers, you often use repository interfaces (ICourseRepository), domain classes (Course) and services (PhotoService). All these are part of the business logic layer. They represent the core of an application irrespective of any presentation or persistence frameworks.

Note that here I’m talking about repository interfaces and not their implementations. These implementations are part of the data access/persistence layer.

Also, note that the services we have here are responsible for orchestration. For example, when adding a photo to a course, first, you need to store that photo in the file system (or some other kind of storage), and then you need to add it to the database (using a repository interface). Here is an example:

// Store the file first 
var uploadsPath = Path.Combine(host.WebRoot, "uploads");
if (!Directory.Exists(uploadsPath))
    Directory.CreateDirectory(uploadsPath);

var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadsPath, fileName);

using (var stream = new FileStream(filePath, FileMode.Create))
{  
    file.Copyto(stream);
}

// Add a record to the database
var photo = new Photo { FileName = fileName };
repository.Add(photo);
unitOfWork.Complete(); 

You wouldn’t write all this logic inside an ASP.NET Core Controller. Imagine, tomorrow you decide to use a different framework. You want to re-use as much code as possible. By encapsulating this code in a service (PhotoService.AddPhoto()), you can switch from ASP.NET Core to a different framework with less effort.

But wait for a second…

Now, that strongly-opinionated developer comes and says: “But who does replace ASP.NET Core with something else? How often does that happen?” Let’s say never! By moving all this logic from a controller into a service, you put the responsibility where it really belongs. The result is cleaner, slimmer, easier to read and easier to test controllers.

Imagine a restaurant where the chef does it all. He’s at the door, welcoming guests, giving them a table, taking their order, then going in the kitchen, chopping the vegetables, cooking, washing the dishes, then coming out and giving the bill to the guests. Would you go to that restaurant? I hope not!

In a good and organized restaurant, there are a few people each focusing on only one job. The waiters/waitresses are purely responsible for welcoming the guests and giving them the bill. The chef is purely responsible for cooking. He or she doesn’t wash the dishes! By the same token, you should have classes that do only one thing and do it well. This is what we call separation of concerns. You should put the responsibility where it really belongs, even if you’re never going to change the presentation or persistence framework of your application.

So, once again, all your domain classes (Course), repository interfaces (ICourseRepository) and application services (PhotoService) are part of the business logic layer. They represent the core of your application completely decoupled from any presentation and persistence frameworks. This is what Uncle Bob defines as Clean Architecture.

Data Access Layer

This layer is all about persistence. Here we have implementations tightly coupled to Entity Framework (or other frameworks) for persisting and retrieving data. If you’re using Entity Framework, your DbContext belongs in this layer. So do UnitofWork and Repository implementations.

Splitting a Project

Now, a common (and bad) practice I’ve seen some developers do, is that they blindly split an ASP.NET project into multiple class libraries, one for each layer. And with this, they assume just because they have a class library called MyProject.BLL or MyProject.DAL, they have properly layered their application. But that’s not necessarily right.

What matters is the direction of dependency and coupling between classes, not folders or projects. You can easily organize your classes into folders and projects but these classes can be poorly coupled to each other, which results in spaghetti architecture. Read my blog post on the topic:

Should you split your ASP.NET MVC/Core projects?

 

If you learned something from this post, please share it and drop your comments/questions below.

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags: , , , , ,
Comments

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 http://nodejs.org 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.

angular2-tutorial

What is a component?

A component is one of the most fundamental building blocks in Angular 2 apps. Every app consists of at least one component, which we call the root component. A component can include other components, which we call child components. A real-world app is essentially a tree of components.

But what are these components really? A component is a TypeScript class that encapsulates the template, data and behaviour for a view. So, it’s more accurate to call it a view component. That’s what they’re called in React.

As an example, think of Twitter. If you want to build a similar app in Angular 2, you may model your application components like this:

  • app
    • navbar
    • sidebar
    • content
      • tweets
        • tweet

Root component

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


import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>' 
}) 
export class AppComponent { }

As you see, a component is a TypeScript class decorated with @Component decorator. We use decorators (also called annotations) to add metadata to a class. This @Component decorator tells Angular that AppComponent is a component. Note that these decorators are actually functions. So, here, @Component is called and given an object which includes metadata about AppComponent:


@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>' 
})

This object has two properties: template, which specifies the markup that should be rendered when this component is used, and selector, which tells Angular where in the DOM it should render this component. This is a CSS selector. So, my-app here represents an element with the name my-app.

When Angular sees an element like that in the DOM, it’ll create an instance 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.


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

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


<h1>Hello {{title}}</h1>
<span><span>
<button>Click me</button>

We want to display a counter on this view. Every time we click the button, the counter will be increased by one. So, first declare a new field in the component:


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

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


<span>Clicks: {{count}}<span>

Finally, to handle the click event, we need to bind it to a method in our component. When we click the button, the corresponding method in the component will be called.

Change the button declaration as follows:


<button (click)="increaseCount()">Click me</button>

Note the syntax. This is called event binding. So, we put the event name in parentheses and then set to a method in the component.

Now, let’s create this method:


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

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

Save the file and switch back to your browser. Click the button a few times and note the counter.

So, in this article, you learned the basics of components in Angular 2.0 apps. A component encapsulates the template, data and behaviour of a view. We used interpolation to render data and event binding to handle events raised from DOM elements.

In the next part, we’ll look at services and dependency injection. If you want to be notified when I publish the next part, subscribe to my blog below.

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

Hi, my name is Mosh Hamedani and I am the author of several best-selling courses on Udemy and Pluralsight with more than 130,000 students in 196 countries. You can see the list of all my web and mobile development courses on this website.
Tags:
%d bloggers like this: