Angular I. Setting Up Your Angular App

De wikijoan
Salta a la navegació Salta a la cerca

Curs: Angular Fundamentals. Microsoft DEV314x


Introduction to Angular

What is Angular?

Angular is a framework that you can use to build applications using HTML and JavaScript/TypeScript. Some call it a web framework as a result. Using Angular will involve accessing the various libraries that make up the framework.

As the documentation on indicates, "You write Angular applications by composing HTML templates with Angularized markup, writing component classes to manage those templates, adding application logic in services, and boxing components and services in modules.

Then you launch the app by bootstrapping the root module. Angular takes over, presenting your application content in a browser and responding to user interactions according to the instructions you've provided."

Sounds simple, right? Not to worry, we will cover the basics you need to understand this framework and how to get started with it in this course.

If you were asked to explain Angular in a nutshell, you might say that it is a framework that simplifies the creation of rich, interactive, client-side web applications, using data binding. Angular consists of various aspects that are introduced here, briefly, and then covered in more detail throughout the course.

Important Angular Components


All of the Angular apps that you create will be modular in form. This means that you will work with NgModules as a part of your application. When creating small web applications, you may only use one module. Every Angular app must have at least one NgModule. This is the root module and is commonly called AppModule.

You'll learn about creating and using Angular modules in Module 2 of this course.


Angular includes a collection of modules written in JavaScript and these modules form libraries within Angular, provide functionality to use in your apps. Angular libraries are noted by the @angular prefix.

This course will cover some of the common libraries in Angular and how you can install them using the node package manager (npm) and then how to import them into your code in the application. Once installed and imported, the functionality in the library is available to your application.


Angular uses the concept of a component to control aspects of your application. As an example, a component is a class that contains the logic necessary to handle an aspect of a page, called views.

Angular handles creating and destroying these components during the user interactions with your web application.


The view for your component is defined in a template. Templates are simply HTML working with Angular on the proper rendering of the component within the application. Templates use standard HTML tags that you may already be familiar with but Angular will make tags and attributes available for the functional implementations in the template. If you have heard Angular devs talk about the moustache operator or tag, you have already heard about some of the Angular syntax that you will be using.

Data Binding

Interactive and dynamic web applications rely on data. You might be creating an online shopping presence or perhaps reflecting statistics from polling stations in your web application. Updating the user interface when data changes, is a time consuming task with the potential for errors in the data or in the syncing of the data and UI elements.

Angular excels at data binding. You simply add binding to your markup in the templates you create and then tell Angular how the data and UI are connected. Data binding can be one-way or bidirectional.


Directives, in essence, are commands that you give to the Angular engine. Angular will apply the instructions specified by the directive, when it renders the template, to transform the DOM in your page.

You can also have structural and attribute directives as well. They are found within element tags similar to attributes with the structural directive being responsible for altering layouts through DOM elements.

Dependency Injection

The documentation on Angular defines dependency injection (DI) as, “a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.”

Essentially it is a mechanism in which the components of you Angular application resolve any dependencies related to services or components required by your component.

As you progress through the course, these concepts will be explored more fully along with examples of implementations in code to give you hands-on practice and reinforce your understanding.

Introduction to TypeScript

TypeScript is an open source programming language developed and maintained by Microsoft. TypeScript was first made available in October 2012. It was created by Anders Hejlsberg and his team in Microsoft. It is a typed superset of JavaScript that compiles to plain JavaScript. As you may know, JavaScript is the language that web browsers understand, it is also a language that can work on all platforms. TypeScript adds optional static typing and class-based object-oriented programming to JavaScript. TypeScript may be used to develop JavaScript applications for both client-side or server-side (Node.js) execution. Because browsers only understand JavaScript, when you write your application in TypeScript language, you need a compiler that would compile your code and convert it to JavaScript for your application to work. TypeScript is open source, it is being developed on GitHub. If you are interested, read the TypeScript Language specification on GitHub or download it as a docx or pdf

Compatibility with JavaScript

TypeScript is a strict superset of ECMAScript 2015 (ECMAScript 6 or ES6), which is a superset of ECMAScript 5, which is JavaScript that we know today. Therefore, a JavaScript program is also a valid TypeScript program, and a TypeScript program can seamlessly consume JavaScript.

With TypeScript, it is possible to use existing JavaScript code, incorporate popular JavaScript libraries, and call TypeScript-generated code from other JavaScript.

Why TypeScript?

JavaScript is a great language for developing small size applications but when it comes to large applications, things start to get out of control with complex JavaScript code and many shortcomings in the language. Over the course of the last few years JavaScript has grown a lot and has become the way to go to write cross platform applications. JavaScript applications can run on all platforms including mobile, web and desktop. In that sense, an application written in JavaScript can run on any platform and browser. JavaScript has also proven to be the official language of the web. However, JavaScript when first created, was not meant for that, it was mainly designed for simple uses in small applications. With the dramatic growth in JavaScript usage, it was time to make it right and fill the gaps that JavaScript misses to have it scale to easily and effectively build medium to large size applications.

In 2010, Anders Hejlsberg and his Microsoft team began their effort to solve this issue by focusing on making JavaScript better and easier. Their vision was to provide a robust solution that would help developers to rely on the language and be more productive with the least amount of errors by catching them earlier during development, rather than run time. They Built TypeScript and made it available for the developers community in 2012.

  • TypeScript solves all the problems with JavaScript. It focuses on the developers experience and productivity. TypeScript starts from the same syntax and semantics that millions of JavaScript developers know today. TypeScript compiles to JavaScript code which runs on any browser, any host, any OS, or in any JavaScript engine that supports ECMAScript 3 (or newer).
  • TypeScript has now become the smart choice for writing a modern web or JavaScript-based application. It is also known as “JavaScript that scales”. Some modern web development libraries like Angular (starting version 2) actually have TypeScript as the required language of development in order to be able to use the library in your application.
  • TypeScript enables JavaScript developers to use highly-productive development tools and practices like static checking and code refactoring when developing applications. Types are optional, and type inference allows a few type annotations to make a big difference to the static verification of your code. Types let you define interfaces between software components and gain insights into the behavior of existing JavaScript libraries.
  • There is a lot of supporting tools for TypeScript in almost all the development editors or IDEs.
  • TypeScript allows team based development where different members of the team can work on different components of the application using modules.
  • TypeScript catches issues with your code early during development that normally can't be caught in JavaScript until code is run in the browser, resulting in runtime exceptions and errors in your application.
  • TypeScript is open source with a huge community of support. TypeScript is the third most-loved programming technology in the 2017 Stack Overflow Developer Survey.
  • TypeScript is cross platform and can run on any browser, any host, any OS.
  • TypeScript is backwards compatible and can accept all your existing JavaScript code as valid TypeScript code.
  • TypeScript also implements all the features of ECMAScript 2015 (or ES6) that solves many of the core shortcomings of JavaScript, like classes, modules, arrow functions and more. ES6 is the next version of JavaScript but although it exists, it doesn't run on any browser today and thus is not being used. TypeScript allows developers to use all the ES6 features by providing syntactic sugar on top of ES5 which the TypeScript compiler will transcompile into ES5 compliant JavaScript that today's browser can execute.
  • TypeScript can be used to write both client side code (that runs on a browser) and server side code (that runs on the application server) using the Node.js library. That means with TypeScript, you only learn one language to become a full stack web developer. This is not the case with JavaScript today since JavaScript only runs on the client side and can't be used to write server side code, developers need to develop server side applications with other languages like C#, C++, Java, PHP, ..etc. TypeScript implemented features from ES6
  • Strongly typed variables.
  • Strongly typed function parameters.
  • Classes.
  • Interfaces.
  • Inheritance.
  • Modules which help divide things into building blocks so more than one person can work on developing one application.
  • Support for code refactoring tools because everything in TypeScript can have a type.
  • Support for libraries like Angular and React to use with TypeScript.

TypeScript is open source. It is being developed on GitHub. The TypeScript compiler is implemented in TypeScript and can be used in any JavaScript host.

Introduction to Angular CLI

Introducing the Angular CLI

Angular CLI is a command-line interface that you can use when creating Angular applications. From this command-line tool you can create projects, add files to existing projects, test, debug, and deploy your Angular applications. You will often find that developers use the Angular CLI to “scaffold” their application. Scaffolding is a concept related to setting up the framework or structure of your application with the core necessities.

You will learn to install the Angular CLI in the lab area of this module but essentially you will be using the node package manager (npm) to install the cli. You will then begin using the Angular CLI as you progress through the labs in this course.

Why Should we Use Angular CLI?

As we mentioned in the Introducing Angular CLI topic, a common use for the CLI is to scaffold an application. When you first begin to create a web application or an Angular application, you may not want to start from scratch with a blank template. Perhaps your organization wants to standardize on templates and boilerplate code.

The Angular CLI can help you create and organize a project structure, follow style guides, and create optimized builds for your Angular applications. The CLI can also help with unit and end testing.

You'll become more familiar with the Angular CLI as you move through the labs in this course.

Angular App Overview

Basic application architecture.


$ ng new angular-test

crea tots els fitxers necessaris en el directori (scaffold) i instal·la els paquets necessaris via npm. so as you can see we have a lot of

  • package.json: contain all of the npm attributes and dependencies for your package
  • tsconfig: drives the typescript compiling for this application and gives you all of the different configuration options there.
  • tslint: drive the linter for typescript in this particular application, which we'll go through and check for bad syntax within your code and making sure everything's up to typescript standards.

testing frameworks in place that come built-in with the angular CLI:

  • karma, which is a unit testing framework. karma is run by .spec files that are contained within your app directory
  • protractor, which is an end-to-end testing framework.


$ start angular-test
$ cd ./angular-test
$ ng serve -o

i aleshores es compila tota l'estructura de fitxers i directoris. Un cop finalitzat ja podem anar al navegador web:

App works!

Labs Overview And Config

  • Install Visual Studio Code
  • Install Prerequisites:

Node, NPM, TypeScript, and the Angular CLI.

  • Using the Angular CLI

you will learn the basics of using the Angular CLI to generate components within your app, and to run your app locally.

Tutorial Lab: Install Visual Studio Code

Tutorial Lab: Installing Prerequisites

To Install TypeScript

TypeScript is a superset of the JavaScript language that allows for stricter typing, along with a series of other features. Angular uses TypeScript instead of JavaScript. Now that we have Node and NPM installed, we can install TypeScript, the last prerequisite needed before installing the Angular CLI.

Installing TypeScript requires administrative privileges. For Windows, this means you need to open a command prompt or terminal with administrative rights. For Mac and Linux users, just open a terminal.

To install TypeScript, simply open your command prompt or terminal window and type:

$ sudo npm install typescript -g

The -g flag tells NPM to install TypeScript as a global module, instead of to the directory your terminal is currently pointed it. This will enable you to be able to use the tsc command to compile TypeScript directly, and enable the Angular CLI to be able to use it.

Now that we have installed TypeScript, next we will install the Angular CLI.

To Install the Angular CLI

The Angular Command Line Interface is an optional component for Angular development that offers a series of generators and commands to make developing in Angular simpler and faster.

With the Angular CLI, you can create a scaffold for your app, generate components, modules, and also perform build tasks such as linting your code, serving your app locally, preparing your files for production usage, and using Angular's Ahead of Time compilation to optimize the performance of your app in production environments.

Let's go ahead and use NPM to install the Angular CLI on your machine.

$ sudo npm install @angular/cli -g

Press Enter, and observe the installation occurring (it will take some time). And that's it! Now we have everything installed to start creating our Angular app. In the next lab we will be using the Angular CLI to generate the scaffolding for our application.

Tutorial Lab Using the Angular CLI

To Generate an Application Scaffold using the Angular CLI

Now that we have the Angular CLI installed, we are going to use it to create a scaffold for our application. The term Scaffold refers to the process of generating a generic template of an application based on the standards of how an Angular application should be constructed. A basic folder hierarchy is created following layout and naming best-practices. The folders are then populated with the components necessary to create a basic Angular application. Creating a scaffold sets up the basic files and architecture required for your app to run, and gives you a good pattern to follow. Using the Angular CLI to build your scaffold also gives you a variety of useful tools, including:

  • Linting
  • Unit testing with Karma
  • End to End testing with Protractor
  • Ahead of Time Compilation
  • A built in local server

Let's go ahead and instantiate a scaffold with the Angular CLI.

1. First we need a name for our application. It needs to be alphanumeric (excepting that it can use dash characters), but the dashes must be immediately succeeded by a letter. For this application we are going to call it angular-fundamentals.

2. Open your command prompt and navigate to the directory you want to generate your app in. Note that the CLI will generate a subdirectory with the name angular-fundamentals within that directory.

3. Type the following to instantiate your application.

$ ng new angular-fundamentals

4. Press enter and observe the application building (foto). You now have your application scaffolded. Next, we're going to add an extra component.

To Generate a Module using the Angular CLI

Now that we have our app generated using the Angular CLI, we're going to use the Angular CLI's generator feature to generate a module. Using the built in generator command in the Angular CLI allows you to create components of your application easily without having to worry about properly including the code in your application. The Angular CLI generates the files in the appropriate format and modifies your files to include the newly generated component properly. Some of the different generators that the Angular CLI can run are:

  • Modules: ng g module my-module
  • Components: ng g component my-component
  • Directives: ng g directive my-directive
  • Pipes: ng g pipe my-pipe
  • Services: ng g service my-service
  • Classes: ng g class my-class
  • Guards: ng g guard my-guard
  • Interfaces: ng g interface my-interface
  • Enums: ng g enum my-enum

Let's generate a module using the Angular CLI Generator function.

1. Open your command prompt or terminal and navigate to your angular-fundamentals directory that you created in the last section.

2. Run the following command:

$ ng g module first-module

Note that first-module is the name of the module you are creating.

(Es crea el mòdul, veure la sortida per pantalla)

3. Obrir el fitxer first-module.module.ts i fixar-se en el contingut. NOTE: You will find this file inside the first-module directory under the app directory in the src directory. src\app\first-module

You've generated a module. Next, we're going to learn how to serve your app using the Angular CLI.

To Use the Angular CLI to Run your App Locally

One of the most useful features about using the Angular CLI is the ability to serve your app locally in order to test it in real time. Serving your app compiles your modules for use and runs a server on your computer. You can then access the app via a browser. In addition, the Angular CLI will listen to changes to your files and recompile your app, meaning you can edit code, and then immediately see the changes in your browser.

Let's serve the app we made now.

1. Open your command prompt and navigate to the angular-fundamentals app we generated earlier.

2. Type the following:

$ ng serve

You should see the following:

4. Open up a browser and navigate to http://localhost:4200.

5. Now, let's make a small change. Open up the file angular-fundamentals/src/app/app.component.ts in Visual Studio Code. Line 9 looks like this:

  title = 'app';

Canviar-ho per:

  title = 'GitHub Browser'g

Save the file, then go back to your console. You will something similar to the following after the original output:

webpack: compiling...

I si tornem al navegador veiem que s'ha actualitzat els canvis.

You have now generated your first app using the Angular CLI and served it to your browser. In our next module, you will begin to build your app within the scaffold that you have created.

creat per Joan Quintana Compte, març 2019