Which is the best Angular 4 tutorial

Angular Tutorial - Part 1: Tools and Getting Started

In this part of our German-language Angular tutorial you will learn the following aspects:

 

Angular is one of the most popular frameworks for modern web-based business applications. In this German-language tutorial, we show how you can use it to develop an initial application that receives data from a backend via HTTP:

While this first part is devoted to the tools and anatomy of an Angular application, the second part is based on the development of the application.

Become an Angular professional with our training courses

From Angular practice training for beginners & autodidacts to advanced workshops for advanced users to Angular Deep Dives for experienced users. In our seminars, participants learn everything they need as a developer for successful Angular projects.

Tools

Here we go into the necessary tools for developing with Angular.

Visual Studio Code

In this book we use the free development environment Visual Studio Code. It works on all major operating systems (Linux, OSX, Windows) and is extremely lightweight. Visual Studio Code also supports the TypeScript language. This is a type-safe superset of JavaScript that is used for Angular development.

There are also numerous extensions that simplify working with frameworks such as Angular. To install extensions, click the icon Extensions in the left icon bar. After that, you can search for extensions and install them:

Useful extensions for Visual Studio Code

We recommend the following extensions for developing Angular solutions:

Angular Language Service

The Angular Language Service is provided by the Angular team and allows Angular-related code completion in HTML templates. The language service also indicates possible errors in HTML templates.

Angular Schematics

Allows building blocks such as Angular components to be generated via the context menu of Visual Studio Code.

Debugger for Chrome

Allows debugging of JavaScript applications running in Chrome.

In addition to Visual Studio Code, we have also had very good experiences with the commercial products WebStorm, PhpStorm and IntelliJ from Jetbrains. These three solutions are actually the same product in different forms. PhpStorm, for example, also supports PHP while IntelliJ also brings many amenities for Java developers with it. Although these solutions are a little heavier than Visual Studio Code, they offer numerous features, such as extensive refactoring options or test runners for unit tests, ex works.

In fact, Visual Studio Code and WebStorm / IntelliJ are by far the most common development environments that we come across in our customer projects in the Angular environment.

Angular CLI

In order not to lose time setting up all the tools required, the Angular team offers the so-called Angular Command Line Interface, or Angular CLI for short. This CLI not only generates the basic structure of the application, but also the basic structure of other application components such as B. Components.

She also takes care of configuring the TypeScript compiler and a build configuration for generating optimized bundles. The CLI also sets up tools for test automation.

The CLI can be easily accessed via the Package Manager npm which is included in the scope of delivery of Node.js. It also uses Node.js as a runtime environment. You should therefore download and install the current Node.js version of Node.js in preparation. We have had good experiences with the respective long-term support versions (LTS versions). Using older versions can lead to problems.

As soon as Node.js is installed, the CLI can be set up using npm:

The desk -G causes npm sets up the tool system-wide, i.e. globally, so that it is available everywhere. Without this switch it would npm just set up the addressed package for a local project in the current folder. After the installation, the CLI is available via the command ng to disposal.

Project start

Generate a project with the CLI

A call from

generated the skeleton of a new Angular application called flight app receives. In addition, it asks us a few questions:

Depending on the Angular version, these questions can vary somewhat. We assume the following settings:

Enforce stricter type checking

Answer this question with yes. This means that more programming errors are found during compilation.

Add angular routing

We answer this question here with no. Routing is a topic of its own.

Style sheet format

We recommend SCSS here, a superset of CSS. The Angular CLI compiles these files for the browser according to CSS.

There ng new also numerous packages via npm the call may take a little longer.

Start Angular application

To start your application, switch to the generated project folder. You will help build there ng serve the application and make it available via a demo web server:

The desk -O opens a browser that displays the application. By default, this application can be found at http: // localhost: 4200. If port 4200 is already occupied, ask ng serve for an alternative. Also, the switch takes --port the desired port at the start of ng serve opposite:

The application displayed in the browser looks like this. Here, too, there may be deviations from version to version:

The command intended for development ng serve but does a little more: it monitors all source code files and triggers the compilation and generation of the bundles again if they change. Then it also updates the browser window.

To try this out, you can use Visual Studio Code to open the src \ app \ app.component.html open and the first occurrence of Welcome by Hello World! to change. Then should ng serve Recompile the affected part of the application, bundle it and update the browser:

If you are using Visual Studio Code, you should first find the main folder of your Angular application with the command File | Open folder to open. The main folder is the one that also contains the file package.json includes. This ensures that Visual Studio Code finds all configuration files and does not display unnecessary errors.

You can then search for and open the desired file using the Explorer displayed on the left. Alternatively, there is a combination Ctrl + p at. It opens a small window that you can use to search for the file you want.

With CTRL + SHIFT + c By the way, you can open an external console in the current folder at any time to e.g. B. run the Angular CLI. The combination CTRL + SHIFT + รถ, on the other hand, opens the console as a terminal directly in Visual Studio Code.

The automatic generation of the bundles after a change to the program code usually works very well, but every now and then the CLI gets out of step. That is, among other things. this is the case when you save several files in quick succession. Renaming files also disrupts this mechanism.

This can be remedied by saving the files concerned again or - if all else fails - restarting ng serve.

Build with CLI

While ng serve is very convenient for development, it is not suitable for production use. Use the instruction to generate bundles for production

The desk --prod activates numerous optimizations that lead to smaller bundles. An example of this is minification, which removes unnecessary characters such as comments or carriage returns and replaces your instructions with shorter counterparts. Another example is so-called tree shaking, which identifies and removes framework components that are not required. Of course, these tweaks slow down the build process a bit.

The generated bundles can be found in the folder dist / flight-app. As part of the deployment, all you need to do is copy these files to the web server of your choice. Since this is a static web application from the point of view of the web server, you do not need to install any additional script language or web framework there.

Project structure of Angular projects

The project structure generated by the CLI is based on best practices that can also be found in other projects:

Folder / filedescription

src /

Contains all source code files (TypeScript, HTML, CSS etc.)

src / main.ts

This source code file is of particular importance. The CLI uses it as an entry point into the application. Therefore your code will be executed first when the program starts. By default it includes a few lines to start Angular. Usually you do not need to modify this file.

src / styles.scss

Here you can enter your own global styles. The file extension, e.g. B. CSS or SCSS, depends on the option selected when generating the project.

src / app /

This folder and its subfolders contain the developed program files such as Angular components.

src / assets /

Folder with static files that the CLI copies to the output directory during build. You could store images or JSON files here, for example.

dist /

Includes the from ng build generated bundles for delivery on a server. The use of ng serve however, does not write these bundles to the disk, but only keeps them in main memory.

node_modules /

Contains all modules that are available over npm were obtained. This includes the TypeScript compiler and other tools for the build, but also all the libraries for Angular.

tsconfig.json

Configuration file for TypeScript. For example, it specifies that the TypeScript compiler should compile your source code according to EcmaScript 2015. This is the JavaScript version that has been supported by all modern browsers in recent years. Via the file .browserslistrc the CLI can be instructed to generate EcmaScript 5 bundles for Internet Explorer 11 as well.

.browserslistrc

Lists all browsers that the Angular application should support. To z. B. to also support Internet Explorer 11 is the entry not IE 11 by IE 11 to replace.

package.json

References all libraries that are required, including the desired versions. If you take a look at the sections dependencies and devDependencies throw, you see all of ng new installed packages. Since the node_modules folder with these packages is not checked into the source code management, these notes are necessary. All your colleagues need is the instruction npm install run to them in the node_modules Load folder.

index.html

The home page. The build process adds references to the generated bundles.

angular.json

This file can be used to adapt the behavior of the CLI. For example, it references global styles or scripts that need to be integrated.

Now let's look at a couple of the program files below src / app take a closer look. Let's start with the generated AppComponent. Like most Angular components, it consists of several files:

app.component.ts

TypeScript file that defines the behavior of the component.

app.component.html

Html file with the structure of the component.

app.component.scss

Local styles file for the component. General styles can be found in the discussed styles.scss be entered.

The following listing shows the content of the generated app.component.ts:

It's a class that has just one property title of the type string owns. The latter does not have to be explicitly stated here: TypeScript can derive this fact from the assigned default value.

The specification of export defines that the class can also be used in other files of the application.

The class was with the decorator Component Mistake. Decorators define metadata for program constructs such as B. Classes. The component imports this from the package in the first line @ angular / core. When using a decorator, the symbol @ prefixed.

The metadata contain the selector of the component. This is usually the name of an HTML element that represents the component. To call the component, you can use the following notation in an HTML file:

The decorator also references the component's HTML template and its SCSS file with local styles. The latter is empty by default. The HTML file contains the code for the start page considered above. It's nice, but it contains a lot of HTML markup. Replace the one to try it out entire Content of this HTML file through this fragment:

If you now start the application (ng serve -o) you should see the content of the property title see as headline. The two pairs of curly braces define a so-called data binding. Angular therefore binds the specified property to the respective position in the template.

More information about data binding and Angular in general can be found in the next part of this tutorial. To complete this tour of the generated program files, however, we would like to point out three more generated files. One of them is the file app.module.tswhich includes an Angular module:

Angular modules are data structures that combine building blocks that belong together like components. Technically, this is another class. In most cases it is empty and only serves as a carrier for metadata that is available via the NgModule-Decorator to be specified.

Let's take a look at the properties of NgModule throw:

declarations

Defines the content of the module. Currently they are limited to ours AppComponent. This is shown in the third line, specifying a relative path to the file app.component.ts references, imported. The file extension .ts is omitted here.

imports

Imports further modules. The example shown only imports that BrowserModule, which includes everything to run Angular in the browser. This is also the standard case.

providers

Here you could register so-called services that offer logics for several components.

bootstrap

This property refers to all components that are to be created when the application is started. Often this is just a single component. This so-called root component represents the entire application and calls up additional components for this purpose.

The module that provides the root component is also referred to as the root module. Angular receives it when the application starts and renders the root component to be found in it. The CLI has the file for this task main.ts set up:

The function platformBrowserDynamic creates a so-called platform that enables Angular to run in the browser. Other platforms enable, for example, the server-side execution of Angular or the execution in mobile applications. However, the use in the browser is the standard case considered here.

The method bootstrapModule accepts the root module and Angular then renders its root component.

The property used environment.production informs whether with ng build --prod a build is requested for production. As mentioned above, this causes the CLI to perform optimizations. However, we can also react to this within the application: In this case, for example, Angular's production mode is also activated. In this mode, Angular is faster, but also generates fewer and less legible error messages.

To determine where on the page our root component is to be displayed, the generated index.html calls it:

During the build, the CLI also supplements this index.html with references to the bundles created. One of them contains the code of the file main.tswhich starts the Angular application.

Install a style library

Since "the eye is also programmed", we want to bring a few predefined styles into play at this point.

Paper design and bootstrap

The theming used here is that Paper design Theme by Creative Tim (https://www.creative-tim.com), which in turn is based on the popular library bootstrap (http://getbootstrap.com) based.

The advantage of Bootstrap, in addition to its extremely widespread use, lies in the fact that it is unobtrusive. It only defines a few (S) CSS classes that can be applied to known HTML elements. In contrast to other solutions, you do not have to learn any further HTML elements at first.

You can install both Bootstrap and Paper Design Theming with the following command:

This package provided by us contains the styles discussed and also generates some configuration entries as well as the skeleton of our application:

As you can see here, this command moves the AppComponent and the AppModule in the folder bak (see lines with RENAME). Then he generates the two again in the folder src / app. It also generates a NavbarComponent, one SideBarComponent and an Angular logo. After that, this call extends from ng add the files angular.json and index.html. The former receives references to the style files from Bootstrap and the free Paper design Themings by Creative Tim. The latter receives two link-Elements for loading the web fonts used by the theming.

By the way, you can also see the from here ng new generate file src / styles.scss, in which you can save your own global styles.

Unfortunately reads ng serve global configuration files like the angular.json only when starting the program. If ng serve is already running, you must therefore quit it (Ctrl + c) and restart.

If you start the application again ng serve -o, the following picture results:

On the left you can see the generated SideBarComponent and in the upper area the one that was also generated NavBarComponent. All links are currently still dummies - but that will change as the book progresses.

ng add vs. npm install

The command provided by the Angular CLI ng add installs an npm package and then runs a script that sets up the package in the Angular application.

Instead, you could go with npm install install the package and set it up manually. In the case of Bootstrap, you would have to do this first npm install bootstrap and then the styles offered by Bootstrap in the angular.json enter manually.

Alternatives to Bootstrap

You will find numerous implementations of design systems and component libraries that can be used as alternatives to Bootstrap, both in the open source environment and in the commercial sector. We would like to point out a few that we come across again and again in our practice:

Angular Material (https://material.angular.io)

The official and open source implementation of Google's Material Design for Angular. This is the implementation that Google uses for its 2600+ Angular-based applications.

Clarity Design System (https://clarity.design/)

More and more companies publish the implementations of their design systems. This also includes the well-known virtualization giant VM Ware, which has implemented its Clarity Design Systems for Angular.

PrimeNG (https://www.primefaces.org/primeng/)

With PrimeNG, the manufacturer of the PrimeFaces UI frameworks known in the Java environment offers an extensive and free component library for Angular. In addition, commercial themes and enterprise support are offered.

DevExtreme (https://js.devexpress.com/)

The company DevExpress might be familiar to one or the other, especially since it has been offering sophisticated components for various platforms for several decades. Their commercial product DevExtreme addresses, among other things, Angular applications. It includes the usual

Standard controls and is characterized by an extremely powerful DataGrid. But there is also a very powerful tree and charts control here.

KendoUI (https://www.telerik.com/kendo-ui)

With KendoUI it is similar to DevExtreme: Behind this commercial product is Telerik, a provider of control elements that has been established for decades. In addition to the usual control elements, KendoUI also offers a very powerful grid, tree and chart control.

ag-Grid (https://www.ag-grid.com)

Anyone who is satisfied with their design system, for example implemented with Bootstrap, and only needs a powerful grid, will find what they are looking for at ag-Grid. This commercial solution focuses on providing "the best JavaScript grid in the world," as its manufacturer puts it.

Summary

The project setup for modern JavaScript applications is usually quite complex. You need to configure compilers, install tools for testing, and take care of a build that does numerous optimizations for production use.

The Angular CLI relieves you of many of these tasks and generates a professional setup that sets up many tools for development with Angular. A simple one is enough ng new and you're good to go. However, as with any generated project setup, you need to take a little time to familiarize yourself with the generated files. Especially the generated AppComponent and that generated AppModule you will need to adjust frequently. Fortunately, you can initially regard the numerous configuration files generated as a black box and look up one or the other setting if necessary.

In the next part of this series we will take up the project setup shown and develop a first Angular application with components, the various types of data binding and HTTP access.